Skip to content

Notification Extensions

Notification extensions allow to i.e. display images by manipulating the content of the notification. For more information see the official documentation

Requirements

  • EZPush Version 1.3.0 or higher

Setup

Shared User Defaults

By default, UserDefaults are not shared between applications. Both the Notification Extension and your App need to share information, i.e. a Consumer ID for authentication. In order to exchange these information, both Applications need to be in the same App Group.

We'd recommend to reuse the App's Bundle Identifier with the group. prefix.

Configure EZPush

let config = EZPushConfiguration(
    licenseKey: "YOUR_LICENSE_KEY", 
    group: "YOUR_GROUP_IDENTIFIER"
)
EZPush.current.configure(config, startPeriodicSync: true)
EZPush.current.update(pushNotificationToken: "PUSH_NOTIFICATION_TOKEN") { _, _ in }

Create Notification Service Extension

File -> New -> Target -> Notification Service Extension

Content

In order to display an Image in a notification, add the following code to the Notification Extension.

import EZPush
// other imports

override init() {
    super.init()
    let config = EZPushConfiguration(
        licenseKey: "YOUR_LICENSE_KEY", 
        group: "YOUR_GROUP_IDENTIFIER"
    )
    EZPush.current.configure(config, startPeriodicSync: false)
}

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
    self.contentHandler = contentHandler
    bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

    let message = EZPush.current.parseCommand(request.content.userInfo)

    EZPush.current.sendReport(for: message, is: ReportType.delivered)

    defer {
        contentHandler(bestAttemptContent ?? request.content)
    }

    guard let attachment = request.attachment else { return }
    bestAttemptContent?.attachments = [attachment]
}

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)
    }
}

Troubleshooting

Notifications not received

Depending on the build type, the Push Token that is generated after the notification request was granted may be for the sandbox/development environment of the Apple Push Service. If you want to test a release version, use ad-hoc builds or deploy a version to Testflight.

Cycle inside AppName; building could produce unreliable results.

Solution: Go to Project -> Target -> Build Phases and move Embed Foundation Extension above Run Script. Source