handling local push notifications when app is in the background

橙三吉。 提交于 2021-01-28 11:12:34

问题


In iOS 10, I see that there are two functions for handling local push notifications:

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

and

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)

The first is invoked when a push notification happens when the app is in the foreground. The second occurs when a push notification happens when the app is in the background AND the user clicks on the notification.

My question is, is there a way to handle a local push notification when the app is in the background WITHOUT the user having to click on it? Ideally, I'd like all of my push notifications, whether while the app is in the background or foreground, to trigger a CloudKit update. Is this even possible?

Thanks!


回答1:


The only way I can think of is adding a Notifications Extension to your app. There are two types: "Notification Service Extension" and "Notification Content Extension".

Both are originally meant for something else, however both could work for this scenario, since both of them can implement the method didReceive(_:withContentHandler:), and if the app is in the background, it's up to the extension to receive and react to the notification.

I recommend using a "Notification Service Extension" (it's originally meant for changing the notification's content right before displaying it, but you could just leave it unmodified), and implementing the didReceive(_:withContentHandler:) method. Simply invoke the content handler with the same original notification and also trigger the CloudKit update.

Here's a good tutorial on how to add the service extension: https://code.tutsplus.com/tutorials/ios-10-notification-service-extensions--cms-27550

In its section "3. Extension Code" there's an example of how to implement the method, with a comment that says "// Edit properties of copy", that's exactly where I would add the code to trigger the CloudKit update, so it's executed right before showing the notification whenever the app is on the background.



来源:https://stackoverflow.com/questions/43989656/handling-local-push-notifications-when-app-is-in-the-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!