Creating a simple UNNotificationContentExtension

suggest change

Step 1: Prepare the app for notifications

Enable the Push Notifications capability when this extension will display remote notifications. A notification content extension does not need Background Modes.

Step 2: Creating a UNNotificationContentExtension

Click the + button at the bottom of the target list, select Notification Content Extension, click Next, name the content extension, and click Finish.

Step 3: Configuring the Info.plist file of the created extension

The NSExtension dictionary controls how the notification content is displayed. The extension appears when the user long-presses the notification.

Step 4: Creating UNNotificationAction and UNNotificationCategory in our application

In the app’s AppDelegate.swift, inside didFinishLaunchingWithOptions, add:

let userNotificationAction = UNNotificationAction(identifier: "ID1", title: "வணக்கம்", options: .destructive)
let userNotificationAction2 = UNNotificationAction(identifier: "ID2", title: "Success", options: .destructive)

let notifCategory = UNNotificationCategory(identifier: "CATID1", actions: [userNotificationAction, userNotificationAction2], intentIdentifiers: [], options: .customDismissAction)

UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().setNotificationCategories([notifCategory])
UIApplication.shared.registerForRemoteNotifications()

This creates two UNNotificationActions, ID1 and ID2, and adds them to a UNNotificationCategory whose identifier is CATID1. That identifier must match UNNotificationExtensionCategory in the content extension’s Info.plist and the category value in the payload. intentIdentifiers lists Siri intent identifiers, not action identifiers, so this example passes an empty array. The category is registered with the app’s UNUserNotificationCenter. registerForRemoteNotifications() does not ask for permission. Call requestAuthorization(options:completionHandler:) first, then register. A successful registration calls application(_:didRegisterForRemoteNotificationsWithDeviceToken:).

Note: import UserNotifications in AppDelegate.swift and adopt UNUserNotificationCenterDelegate.

Step 5: Sample payload for the notification content

{
  "aps": {
    "badge": 0,
    "alert": {
      "title": "Rich Notification",
      "body": "Body of RICH NOTIFICATION"
    },
    "sound": "default",
    "category": "CATID1",
    "mutable-content": 1
  },
  "attachment": "2"
}

category must be CATID1 for this extension to appear. mutable-content must be the number 1 when a notification service extension should also run; the content extension does not require it. attachment is a custom key outside aps.

Step 6: Configuring the content extension

The actions for that category appear when the user expands the notification. This code updates the extension interface and must call the completion handler.

import UIKit
import UserNotifications
import UserNotificationsUI

class NotificationViewController: UIViewController, UNNotificationContentExtension {

    @IBOutlet var imageView: UIImageView?
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func didReceive(_ notification: UNNotification) {
        self.title = "Koushik"
        imageView?.backgroundColor = UIColor.clear
        imageView?.image = UIImage(named: "welcome.jpeg")
    }

    func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
        self.title = "Koushik"

        if response.actionIdentifier == "ID1" {
            imageView?.image = UIImage(named: "Success.jpeg")
        } else {
            imageView?.image = UIImage(named: "welcome.jpeg")
        }

        completion(.dismiss)
    }
}

Step 7: Result

After the notification arrives, long-press it or tap View. It looks like this:

The title is “Koushik” because the code sets self.title = "Koushik" and UNNotificationExtensionOverridesDefaultTitle is YES. In step 3, UNNotificationExtensionDefaultContentHidden is NO. When that key is YES, the notification looks like images 3 and 4.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents