【问题标题】:iOS: Issue in updatating devicetoken after initial rejection of permission for push notification?iOS:初始拒绝推送通知权限后更新设备令牌的问题?
【发布时间】:2017-01-12 03:07:11
【问题描述】:

我制作了一个提供推送通知的应用程序。设备令牌更新存在问题。当用户在安装应用程序后立即授予推送通知权限时,设备令牌正在更新。但是如果用户在安装应用后拒绝权限,然后在设置中授予权限,那么设备令牌仍然显示为空。

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

这是我实现的代码。

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

【问题讨论】:

    标签: ios swift apple-push-notifications


    【解决方案1】:

    您应该检查 applicationWillEnterForeground 中的权限

    更多参考示例代码

    斯威夫特 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()
    
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 2017-03-03
      • 1970-01-01
      • 1970-01-01
      • 2015-08-29
      相关资源
      最近更新 更多