Modify the payload of a remote notification before it's displayed on the user’s iOS device.
You may want to modify the content of a remote notification on a user’s iOS device if you need to:
Decrypt data sent in an encrypted format.
Download images or other media attachments whose size would exceed the maximum payload size.
Update the notification's content, perhaps by incorporating data from the user's device.
Modifying a remote notification requires a notification service app extension, which you include inside your iOS app bundle. The app extension receives the contents of your remote notifications before they are displayed to the user, giving you time to update the notification payload before the user is alerted. You control which notifications are handled by your extension.
Add a Service App Extension to Your Project
A notification service app extension ships as a separate bundle inside your iOS app. To add this extension to your app:
Select File > New > Target in Xcode.
Select the Notification Service Extension target from the iOS > Application section.
Specify a name and other configuration details for your app extension.
Implement Your Extension's Handler Methods
The notification service app extension template provided by Xcode includes a default implementation for you to modify.
servicemethod to terminate any payload-modification tasks that are still running.
Extension Time Will Expire()
did method has only about 30 seconds to modify the payload and call the provided completion handler. If your code takes longer than that, the system calls the
service method, at which point you must return whatever you can to the system immediately. If you fail to call the completion handler from either method, the system displays the original contents of the notification.
Listing 1 shows an implementation of the
UNNotification object that decrypts the contents of a secret message delivered using a remote notification. The
did method decrypts the data and returns a modified version of the notification’s content if it is successful. If it is unsuccessful, or if time expires, the extension returns content indicating that the data is still encrypted.
Configure the Payload for the Remote Notification
The system executes your notification content app extension only when a remote notification’s payload contains the following information:
The payload must include the
mutable-contentkey with a value of
The payload must include an
alertdictionary with title, subtitle, or body information.
Listing 2 shows the JSON data for a notification payload containing encrypted data. The
mutable-content flag is set so that the user’s device knows to run the corresponding service app extension, the code for which is shown in .