如何在iOS中获得One Signal用户的唯一玩家ID?

azn*_*e89 13 push-notification ios swift onesignal

如何在iOS中检索OneSignal用户的唯一玩家ID?我只在OneSignal官方文档中找到了iOS SDK设置.

谢谢,如果有任何建议.

Gab*_*rra 30

您需要使用OneSignal的观察者,例如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)")
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

有关更好的解释,请参阅addSubscriptionObserver的文档


MBH*_*MBH 17

我需要在我的代码中的某处获取Player Id(或UserId),我不想将它保存在任何地方.

我最终使用了这段代码:

let userId = OneSignal.getPermissionSubscriptionState().subscriptionStatus.userId
Run Code Online (Sandbox Code Playgroud)