Need explanation about requesting permission for notifications in iOS

955 Views Asked by At

Info about "authorization"

Info about "requesting permission"

The problem is they both needed in the same code but they are split into 2 separate articles. So it is unclear how to deal with them simultaneously and what is the difference between them (of course except of input params).

The code I found just calls these functions sequentially:

UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in
  ...
})
UIApplication.shared.registerForRemoteNotifications()

Is it correct? And what is the difference between these methods?

P.S. I also can't simply place them inside application:didFinishLoad: according to the documentation because the app shouldn't request permissions from the very first run.

1

There are 1 best solutions below

1
On BEST ANSWER

This

UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in
  ...
  // code here
})

Asks the user whether he accepts receive notification which actually will show the popup , but this ( used for push notifications not local )

UIApplication.shared.registerForRemoteNotifications()

According to Docs

Call this method to initiate the registration process with Apple Push Notification service. If registration succeeds, the app calls your app delegate object’s application:didRegisterForRemoteNotificationsWithDeviceToken: method and passes it a device token.

//

if #available(iOS 10.0, *) {
    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })

    // For iOS 10 display notification (sent via APNS)
    UNUserNotificationCenter.current().delegate = self

} else {
    let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
    application.registerUserNotificationSettings(settings)
}

application.registerForRemoteNotifications()