How to get One Signal user's unique player id in iOS?

aznelite89 picture aznelite89 · Jun 8, 2017 · Viewed 11.2k times · Source

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.

Answer

GabrielaBezerra picture GabrielaBezerra · Jun 9, 2017

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