gpt4 book ai didi

iOS:在最初拒绝推送通知权限后更新 devicetoken 时出现问题?

转载 作者:行者123 更新时间:2023-11-28 08:20:03 24 4
gpt4 key购买 nike

我制作了一个提供推送通知的应用程序。 devicetoken 更新存在问题。当用户在安装应用程序后立即授予推送通知权限时,将更新 devicetoken。但是如果用户在安装App后拒绝权限,后来在设置中授予权限,那么device token还是显示为null。

如果有人可以帮助我在安装应用程序时最初拒绝权限后用户授予推送通知权限后如何获取设备 token ,我将不胜感激。

这是我实现的代码。

    func registerForPushNotification(_ application: UIApplication) {
// set notification types
let types: UIUserNotificationType = [.alert, .badge, .sound]
let notificationSettings = UIUserNotificationSettings(types: types, categories: nil)
application.registerUserNotificationSettings(notificationSettings)
// register
application.registerForRemoteNotifications()
}

// success fetching device token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

let tokenChars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
var deviceTokenString = ""

for i in 0..<deviceToken.count {
deviceTokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}

print("Device token \(deviceTokenString)")

// register device token
Service.sharedService.registerDeviceToken(deviceTokenString, completion: { (error) -> Void in
if error != nil {
print("Device token not registered: \(error.localizedDescription)")

} else {
print("Device token registered!")
}
})

}
// failed fetching device token
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Error registering for remote notifications: \(error.localizedDescription)")
}

最佳答案

您应该在 applicationWillEnterForeground 中检查权限

更多引用示例代码

swift 2.0

optional func applicationWillEnterForeground(_ application: UIApplication) {
let notificationType = UIApplication.sharedApplication().currentUserNotificationSettings()!.types
if notificationType == UIUserNotificationType.None {
// Push notifications are disabled in setting by user.
}else{
// Push notifications are enabled in setting by user.
// need to call again register remote notification code
// set notification types

let types: UIUserNotificationType = [.alert, .badge, .sound]
let notificationSettings = UIUserNotificationSettings(types: types, categories: nil)
application.registerUserNotificationSettings(notificationSettings)
// register
application.registerForRemoteNotifications()

}
}

关于iOS:在最初拒绝推送通知权限后更新 devicetoken 时出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41592177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com