Do remote push notifications require to add UIBackgroundModes in Info.plist?

后端 未结 5 2077
自闭症患者
自闭症患者 2021-01-30 19:25

I have integrated remote push notifications, but I am getting this warning:

didReceiveRemoteNotification:fetchCompletionHandler:], but you st

5条回答
  •  温柔的废话
    2021-01-30 19:46

    In fact, you do not need to add UIBackgroundModes to .plist simply to use remote notifications.

    I know I'm splitting heirs a bit (the other answer is mostly great, and perhaps something is new as of iOS 11), but the question refers to push notifications necessitating background updates, and they do not.

    The distinction here, is that there are two different methods that accept notifications on the AppDelegate;

    This one does not require you to use UIBackgroundModes:

    optional func userNotificationCenter(_ center: UNUserNotificationCenter, 
                             willPresent notification: UNNotification, 
                   withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    

    The above replaces the deprecated as of iOS 11:

    optional func application(_ application: UIApplication, 
    didReceiveRemoteNotification userInfo: [AnyHashable : Any])
    

    And this one does require background modes capability:

    optional func application(_ application: UIApplication, 
    didReceiveRemoteNotification userInfo: [AnyHashable : Any], 
       fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
    

    The key thing here, is the former one (and the deprecated one it replaced) only runs when the app is in the foreground. The latter will run if the app is in the foreground OR background. See the spec for this specific nugget:

    Use this method to process incoming remote notifications for your app. Unlike the application(_:didReceiveRemoteNotification:) method, which is called only when your app is running in the foreground, the system calls this method when your app is running in the foreground or background.

    Hence, if you need push notifications, then decide if you need to run in the background - only if you need both should you implement the method suggested by the warning.

提交回复
热议问题