如何在iOS中检索OneSignal用户的唯一玩家ID? 我只在OneSignal官方文档中找到了iOS SDK设置。
如果有任何建议,谢谢。
答案 0 :(得分:27)
您需要使用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
的文档答案 1 :(得分:14)
我确实需要在我的代码中的某处获取Player Id(或UserId),我不想将它保存在任何地方。
我最终使用了这段代码:
let userId = OneSignal.getPermissionSubscriptionState().subscriptionStatus.userId
答案 2 :(得分:0)
let status: OSPermissionSubscriptionState = OneSignal.getPermissionSubscriptionState()
let hasPrompted = status.permissionStatus.hasPrompted
print("hasPrompted = \(hasPrompted)")
let userStatus = status.permissionStatus.status
print("userStatus = \(userStatus)")
let isSubscribed = status.subscriptionStatus.subscribed
print("isSubscribed = \(isSubscribed)")
let userSubscriptionSetting = status.subscriptionStatus.userSubscriptionSetting
print("userSubscriptionSetting = \(userSubscriptionSetting)")
let userID = status.subscriptionStatus.userId // This one
print("userID = \(userID)")
let pushToken = status.subscriptionStatus.pushToken
print("pushToken = \(pushToken)")
答案 3 :(得分:-5)
您可以在standardUserDefaults中找到它。您可以使用以下方法检索它。我相信它是在第一次启动应用时设置的,但是,第一次调用application:didFinishLaunchingWithOptions:
时可能无法设置。
UserDefaults.standard.string(forKey: "GT_PLAYER_ID")
您可以通过查看字典表示来查看用户默认值中还存储了哪些内容:UserDefaults.standard.dictionaryRepresentation()