Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get notification authorization status in swift 3?

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?

like image 878
andre Avatar asked Sep 27 '17 21:09

andre


People also ask

Can you have a custom dialog message when asking for notification permissions?

No, this is system message, you can't change to custom. Save this answer.

What is provisional notification?

Provisional push enables publishers to send notifications to a user's device without explicitly obtaining prior permission. These notifications give users a preview of the type of content sent via push notifications before deciding whether they want to receive them in the foreground.

What is notification in Swift?

Notification object, identified by name , may contain reference to the object that has sent the notification, and some arbitrary information in the userInfo dictionary. NotificationCenter registers observers and delivers notifications. Objects use NotificationCenter instance to post and observe a notification.


2 Answers

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

like image 73
andre Avatar answered Nov 19 '22 21:11

andre


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

like image 27
Simon Bøgh Avatar answered Nov 19 '22 19:11

Simon Bøgh