iOS:最初拒绝推送通知权限后更新devicetoken的问题?

时间:2017-01-11 13:25:51

标签: ios swift apple-push-notifications

我制作了一个提供推送通知的应用程序。 devicetoken更新存在问题。当用户在安装应用程序后立即授予推送通知权限时,将更新devicetoken。但是,在安装App之后用户拒绝权限并且稍后在设置中授予权限的情况下,设备令牌仍然显示为null。

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

这是我实施的代码。

    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)")
}

1 个答案:

答案 0 :(得分:0)

您应该检查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()

}
}