2

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:

  1. Power off device
  2. Send push notification to device
  3. Power on device
  4. 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
  }
}
iamarnold
  • 705
  • 1
  • 8
  • 22
  • This is expected behaviour. If you app isn't running it will not be launched into the bsckground due to a push notification. The user needs to launch your app and suspend it – Paulw11 Feb 21 '19 at 20:41

0 Answers0