Ad

UIApplication.shared.isRegisteredForRemoteNotifications Always Return True

- 1 answer

I am working on an app and try to figure out whether my app is registered for Push Notifications or not. I mean user allow Push notifications or not. But when i want to check in code it always return true. i don't know why is it behaving like this.

My code for checking push notifications registration.

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)

    }
}
Ad

Answer

What I understood is that if "isRegistered" is false you will ask the user to allow notifications in that case you should be asking for authorization like this :

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