UIApplication.shared.isRegisteredForRemoteNotifications始终返回true

时间:2018-02-02 16:59:30

标签: ios swift apple-push-notifications

我正在开发一款应用,并尝试确定我的应用是否已注册推送通知。我的意思是用户是否允许推送通知。但是,当我想检查代码时,它总是返回true。我不知道为什么会这样。

我的检查推送通知注册的代码。

let isRegistered = UIApplication.shared.isRegisteredForRemoteNotifications

if isRegistered == false {

    let alertController = UIAlertController(title: "Notification Alert", message: "Kindly enable push notifications", preferredStyle: .alert)
    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }
        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
            })
        }
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)
    alertController.addAction(settingsAction)
    DispatchQueue.main.async {
        self.present(alertController, animated: true, completion: nil)

    }
}

1 个答案:

答案 0 :(得分:1)

我的理解是,如果" isRegistered"是的,你会要求用户允许通知,在这种情况下你应该要求这样的授权:

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        if granted {
            DispatchQueue.main.async(execute: {
                UIApplication.shared.registerForRemoteNotifications()
            })
        }
    }