2
votes

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
If you are using CloudKit then you can use the didReceiveRemoteNotification:completionHandler App delegate methodPaulw11
Well, I'm not actually using remote notifications though. I want my local notification to trigger a function that does an add operation to the database.mlecoz
There are no time-schedule based background execution modes available on iOS.Paulw11

1 Answers

1
votes

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.