How to check if UNNotifications are enabled, after asking for permission?

1k views Asked by At

Currently I have the following code, which is essentially asking the user for permission to send notifications, and then checking to see if notifications are enabled:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) in
        if granted {

        } else {

        }
    })

    let notifType = UIApplication.shared.currentUserNotificationSettings?.types
    if notifType?.rawValue == 0 {
        print("being called")
        let alert = UIAlertController(title: "Notifications are disabled for this app.", message: "Please enable notifications for the app to work properly. This can be done by going to Settings > Notifications > NAME HERE and allow notifications.", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))
        show(alert, sender: self)
    } else {
        //enabled
    }

The code works, however, it checks if notifications are enabled before the user can select "yes" or "no". Thus, no matter what is selected, the dialog box pops up. Is there a way I can wait to check for authorization status until the user selects "yes" or "no"?

1

There are 1 answers

0
Dominic K On BEST ANSWER

You can move the check into the callback, so authorization is checked first:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) in
    if (granted) {
        // Alert here
    } else {
       // Or here
    }
})