需要有关在 iOS 中请求通知权限的说明

Need explanation about requesting permission for notifications in iOS

Info about "authorization"

Info about "requesting permission"

问题是它们都需要用在相同的代码中,但它们被分成了 2 篇单独的文章。所以不清楚如何同时处理它们以及它们之间有什么区别(当然除了输入参数)。

我找到的代码只是顺序调用了这些函数:

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

是否正确?这些方法有什么区别?

P.S。根据文档,我也不能简单地将它们放在 application:didFinishLoad: 中,因为应用程序不应从第一个 运行.

请求权限

这个

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

询问用户是否接受实际上会显示弹出窗口的接收通知,但这(用于非本地推送通知)

UIApplication.shared.registerForRemoteNotifications()

根据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()