Sobes.tech
Middle

What is a notification service extension?

sobes.tech AI

Answer from AI

Notification Service Extension is a small executable supplement embedded in your iOS app. It allows you to modify the appearance of remote push notification content before it is displayed to the user.

Main functions:

  • Content modification: Changing the title, subtitle, text, or adding attachments (images, videos) to the notification.
  • Decrypting Encrypted Content: Decrypting encrypted data sent along with the notification before displaying it to the user.
  • Rich Notifications: In conjunction with Notification Content Extension, allows creating custom interfaces for displaying notifications.

Lifecycle:

  1. When a remote notification with the key mutable-content: 1 is received, the system initiates the launch of the Notification Service Extension.
  2. The method didReceive(_:withContentHandler:) is implemented, where the notification is processed and modified.
  3. The modified content is passed to the completion handler contentHandler.
  4. The system displays the modified notification.

Restrictions:

  • Short execution time (usually about 30 seconds).
  • Limited access to system resources.
  • Cannot perform long background tasks.

Example of basic implementation:

import UserNotifications

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 ?? "No Title") [modified]"

            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 delivered.
        if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }

}