事实上,您不需要将 UIBackgroundModes 添加到 .plist 中,只是为了使用远程通知。
我知道我有点毛骨悚然(另一个答案大多很棒,也许是 iOS 11 的新功能),但问题是指需要后台更新的推送通知,而他们没有。
这里的区别在于,有两种不同的方法在 AppDelegate 上接受通知;
这个不需要你使用 UIBackgroundModes:
optional func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
以上内容取代了自 iOS 11 起已弃用的内容:
optional func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any])
而且这个确实需要后台模式功能:
optional func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
这里的关键是,前一个(以及它所取代的已弃用的)仅在应用程序处于前台时运行。如果应用程序在前台或后台,后者将运行。请参阅 the spec 了解此特定金块:
使用此方法为您的应用处理传入的远程通知。
与 application(_:didReceiveRemoteNotification:) 方法不同,它
仅当您的应用程序在前台运行时调用,系统
当您的应用在前台运行时调用此方法或
背景。
因此,如果您需要推送通知,则决定是否需要在后台运行 - 只有在两者都需要时,您才应实施警告建议的方法。