How to retrieve the OneSignal users' unique player id in iOS? I only found iOS SDK Setup in OneSignal Official Documentation.
Thanks if any suggestions are given.
To get the app ID, sign in to your OneSignal account, click on the app or site that you have added to your OneSignal account. The application/site's dashboard opens. Copy the application ID from the URL bar of the dashboard page.
Test that push notifications from OneSignal work. From the Matrix site app dashboard in OneSignal, click MESSAGES and then NEW PUSH on the Messages page. On the New Message page, set the Audience to "Send to Subscribed Users". In the Message section, enter a custom TITLE and MESSAGE for your test push notification.
You need to use OneSignal's observers such as OSSubscriptionObserver.
// Add OSSubscriptionObserver after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSSubscriptionObserver {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Add your AppDelegate as an subscription observer
OneSignal.add(self as OSSubscriptionObserver)
}
// After you add the observer on didFinishLaunching, this method will be called when the notification subscription property changes.
func onOSSubscriptionChanged(_ stateChanges: OSSubscriptionStateChanges!) {
if !stateChanges.from.subscribed && stateChanges.to.subscribed {
print("Subscribed for OneSignal push notifications!")
}
print("SubscriptionStateChange: \n\(stateChanges)")
//The player id is inside stateChanges. But be careful, this value can be nil if the user has not granted you permission to send notifications.
if let playerId = stateChanges.to.userId {
print("Current playerId \(playerId)")
}
}
}
For a better explanation, here is the documentation for addSubscriptionObserver
I do need to get the Player Id (Or UserId) somewhere inside my code, and i dont want to save it anywhere.
I ended up using this code:
let userId = OneSignal.getPermissionSubscriptionState().subscriptionStatus.userId
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With