I'm trying to implement UNNotificationServiceExtension so that I could modify the contents of push notifications before they get shown. It working fine, but I noticed a scenario where push notifications don't go through the UNNotificationServiceExtension.
Steps to reproduce:
- Power off device
- Send push notification to device
- Power on device
- Push notification comes in when device is connected to the wifi/cellular
Result: Push notification doesn't go through the UNNotificationServiceExtension, which modifies the contents of the title and body. It only goes through if I launch the host app before I'm connected to wifi/cellular.
Expected: Push notification should always go through the UNNotificationServiceExtension.
Is this the expected behaviour? Is there no guarantee that push notification always go through the UNNotificationServiceExtension?
Here's my code for the implementation of UNNotificationServiceExtension:
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)
guard let bestAttemptContent = bestAttemptContent else { return }
bestAttemptContent.title = "title has been modified by extension"
bestAttemptContent.body = "body has been modified by extension"
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)
}
}
}
and my payload:
{
"aps": {
"alert": {
"body": "my body",
"title": "my title"
},
"content-available": 1,
"mutable-content": 1
}
}