20

How can I check UNUserNotificationCenter for current authorization status in iOS 11? I've been looking for a while and found some code but it's not in swift 3 and some of functions were deprecated in iOS 10. Can anyone help?

andre
  • 773
  • 1
  • 6
  • 16

2 Answers2

39

Okay I found it:

let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in
    if(settings.authorizationStatus == .authorized)
    {
        print("Push authorized")
    }
    else
    {
        print("Push not authorized")
    }
}

code by: Kuba

andre
  • 773
  • 1
  • 6
  • 16
16

When getting the notification authorization status, there are actually three states it can be in, i.e.

  • authorized
  • denied
  • non-determined

A straightforward way to check these is with a switch-case where .authorized, .denied, and .nonDetermined are enums in UNAuthorizationStatus

UNUserNotificationCenter.current().getNotificationSettings { (settings) in
    print("Checking notification status")

    switch settings.authorizationStatus {
    case .authorized:
        print("authorized")

    case .denied:
        print("denied")

    case .notDetermined:
        print("notDetermined")

    }
}

Description of UNAuthorizationStatus can be found here in Apple's docs https://developer.apple.com/documentation/usernotifications/unauthorizationstatus

Simon Bøgh
  • 801
  • 8
  • 13
  • 1
    Good to hear :) Though in some situations it is very relevant to differentiate between authorized, denied, and not determined, and not only if it has been authorized or not. E.g. if the status is not authorized, there is a big difference in asking the user again for authorization whether it is not determined or they already denied the request. Of course, it depends on the use case ;) – Simon Bøgh May 03 '18 at 10:14
  • Do you know if it is possible to reset the `settings.authorizationStatus` to `.notDetermined` so the system permission dialog is shown to the user again? I require this in case a user logs out and a different users logs in. In this case I'll request again to the UNUserNotificationCenter permission via `requestAuthorization()`, but it does not show the alert again since it is already set by the previous user (e.g. `.authorized' or `.denied`). – Jose Enrique Feb 09 '23 at 16:54