I tried to implement the new Notification Service Extension, but I have a problem.
In my NotificationService.swift file I have this code:
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent {
// Modify the notification content here...
bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
print(bestAttemptContent.body)
contentHandler(bestAttemptContent)
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
When I got a push notification the didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) method never called.
Maybe I misunderstood how this extension is working?
I was getting crazy. Finally I realized that I had the
deployment target
ofNotification Service Extension
was10.3
(my phone too). I changed to10.2
and it works perfectlyFrom docs on
UNNotificationServiceExtension
class:Basically
Must include:
mutable-content: 1
alert
dictionary.Must NOT include:
content-available: 1
To summarize Apple is doing its best to not allow apps to mutate silent notifications. It wants to allow that only on user notifications (user facing notifications)
Your push notification payload should contain the "mutable-content" : 1 key value pair.
Ex of push notification payload JSON:
This works perfectly fine and i get the Push notification as follows:
Also Note That :
You can try Pusher or Houston for testing the Push Notifications.
Check your deployment target on Service Extension.
I had deployment target set to 10.2 when testing on device with 10.1 and extension wasn't called until I changed it.
Another issue might be debugging.. In order to make it work You need to attach Service Extension Process. In Xcode menu Debug > Attach To Process > Name of your extension
Run service extension as the Target instead of the app. Then it will ask for which app you have run service extension, then select your app and it will send the notification.
Make sure the deployment target of the service extension is less that your physical device's OS version.
Ensure payload contains
mutable-content: 1
content-available
flag inaps
or if you've added then make sure it's set to0
.you need to add
"mutable-content": 1
to your payload