How to get One Signal user's unique player id in iOS?
12,591
Solution 1
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
Solution 2
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
Author by
aznelite89
i love technology and enjoyed using apple products and developing application through Xcode. Personally, i like to reading and traveling
Updated on June 03, 2022Comments
-
aznelite89 about 2 years
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.
-
Timur Bernikovich almost 7 yearsI think it's to hard for such thing. OneSignal should print player id in logs.
-
reza_khalafi almost 6 yearsonOSSubscriptionChanged not called.
-
Venkatesh Somu over 5 yearsHi @MBH, when I used the your code let userId = OneSignal.getPermissionSubscriptionState().subscriptionStatus.userId , I am getting the following error "MUST PROVIDE A VALID CALLBACK"
-
Protocol over 5 yearsin my case ononOSSubscriptionChanged not called. Please suggest why it is not called still objserver is add in didFinishLaunching method.
-
Kashif Ahmed over 4 yearsNice Answer actually OneSignal store player id by default into sharePrefrence (Android) and UserDefaults (ioS)