在应用程序启动期间始终调用registerForRemoteNotifications()是否正确?

时间:2019-06-17 09:52:44

标签: ios apple-push-notifications usernotifications

摘自https://developer.apple.com/documentation/usernotifications/registering_your_app_with_apns上的Apple Doc示例

UIApplication.shared.registerForRemoteNotifications()始终在应用启动时被调用:

func application(_ application: UIApplication,
           didFinishLaunchingWithOptions launchOptions:
           [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
   // Override point for customization after application launch.

   UIApplication.shared.registerForRemoteNotifications()
   return true
}

正常吗?还是我们应该使用布尔首选项并检查是否未注册并调用它?

我还需要请求用户授权才能显示通知,但要显示在适当的位置(例如,在我的“设置视图控制器”中,我可以在其中启用/禁用通知)

  UNUserNotificationCenter.current().delegate = self
  let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
  UNUserNotificationCenter.current().requestAuthorization(
    options: authOptions,
    completionHandler: {_, _ in })

在这种情况下,我似乎必须将所有代码从AppDelegate(例如:https://github.com/firebase/quickstart-ios/blob/master/messaging/MessagingExampleSwift/AppDelegate.swift)移到我的“设置视图控制器”,甚至是registerForRemoteNotifications()

因此,与通知(注册,接收)相关的所有委托都将在“设置视图控制器”中。它会起作用吗? App未运行时,我会在那个地方收到通知吗?

还是应该将代码的不同部分放在哪里?

更新

还有为什么他们不使用

UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { settings in
    if settings.authorizationStatus == .notDetermined {
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions) { granted, error in
            if granted {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    } else if settings.authorizationStatus == .denied {
        //
    } else if settings.authorizationStatus == .authorized {
        UIApplication.shared.registerForRemoteNotifications()
    }
})

代替

let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
  options: authOptions,
  completionHandler: {_, _ in })

UIApplication.shared.registerForRemoteNotifications()

1 个答案:

答案 0 :(得分:1)

我认为正确的方法是始终在应用启动时调用registerForRemoteNotifications()。仅当用户获​​得授权的推送通知时才调用它是危险的。实际上,用户最初可以拒绝授权,但随后他可以打开设备“设置”应用中的通知。在这种情况下,除非用户重新打开应用程序,否则应用程序将不会收到通知,这可能会在以后发生。