Let me take it step by step.
UNNotificationServiceExtension - what is it?
UNNotificationServiceExtension is the goal of the Extenstion application that you associate with your application to modify push notifications as and when they are delivered to the device before providing it to the user. You can change the title, subtitles, body and optionally add attachments to the push notification by downloading it or using one in the kit in the application.
How to create
Go to File → New → Target → Notification Service Extension and fill in the data
What key is required to set the push notification payload?
You need to set the mutable-content flag to 1 to trigger a service extension. In addition, if the content-available parameter is set to 1 , the service extension will not work. Therefore, either do not install it, or set it to 0. (Change: this is not applicable. You can set or disable the content-available flag)
How to determine the payload and how to start a service extension from a push notification?
Create an extension, and then create and run the application. Send a push notification with mutable-content to 1 .
code
UNNotificationService provides two functions:
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler; - (void)serviceExtensionTimeWillExpire;
The first function is triggered when a push notification is received on the device and before it is presented to the user. The code inside the function has the ability to change the contents of the push notification inside this function.
You do this by changing the bestAttemptContent property of your extension, which is an instance of UNNotificationContent and has the following properties: title , subtitle , body , attachments , etc.
The original remote notification payload is delivered via the request.content property of the request function parameter.
Finally, you submit your bestAttemptContent using contentHandler:
self.contentHandler(self.bestAttemptContent);
You have limited time to do your things in the first method. If this time expires, your second method is called with the best attempt your code has made so far.
Code example
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { self.contentHandler = contentHandler; self.bestAttemptContent = [request.content mutableCopy]; // Modify the notification content here... self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.title]; self.contentHandler(self.bestAttemptContent); }
The above code adds [modified] to the original header in the PN payload.
Payload Example
{ "aps": { "alert": { "title": "Hello", "body": "body.." }, "mutable-content":1, "sound": "default", "badge": 1, }, "attachment-url": "" }
Please note that the attachment-url key is a custom key for your own problems and is not recognized by iOS.