如何在iOS中检索OneSignal用户的唯一玩家ID?我只在OneSignal官方文档中找到了iOS SDK设置。
谢谢,如果有任何建议。
您需要使用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)")
}
}
}
为了更好的解释,这里是addSubscriptionObserver的文档
我需要在我的代码中的某处获取Player Id(或UserId),我不想将它保存在任何地方。
我最终使用了这段代码:
let userId = OneSignal.getPermissionSubscriptionState().subscriptionStatus.userId
您可以在standardUserDefaults中找到它。您可以使用以下方法检索它。我相信它是在第一次应用程序启动时设置的,但是,它可能不会在第一次调用application:didFinishLaunchingWithOptions:
时设置。
UserDefaults.standard.string(forKey: "GT_PLAYER_ID")
您可以通过查看字典表示来查看用户默认值中存储的其他内容:UserDefaults.standard.dictionaryRepresentation()