Implement actionable push notification for iOS APP in Swift. Use Google Firebase for pushing notifications.

Note

Server send notification using FCM Notification Message type with an identifier. The sample program below use “NOTIFICATION_CUSTOM” as the actionable notification id.

Define actionable notification

Define the actionable notification via UNNotificationCategory & UNUserNotificationCenter

1
2
3
4
5
6
7
8
9
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
...
application.registerForRemoteNotifications()
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self

self.registerCustomActions()
...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private func registerCustomActions() {
// Define the custom actions.
let action1 = UNNotificationAction(identifier: "CUS_ACTION1",
title: "Action1",
options: [.foreground])
let action2 = UNNotificationAction(identifier: "CUS_ACTION2",
title: "Action2",
options: [.foreground])
// Define the notification type
let actionCategory = UNNotificationCategory(identifier: "NOTIFICATION_CUSTOM",
actions: [action1, action2],
intentIdentifiers: [],
hiddenPreviewsBodyPlaceholder: "",
options: .customDismissAction)

// Register the notification type.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.setNotificationCategories([actionCategory])
}

Handle notification actions

Handle the notification actions in userNotificationCenter didReceive function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

print("didReceive notification")
let userInfo = response.notification.request.content.userInfo
let id = response.notification.request.content.categoryIdentifier
print("info \(userInfo) \(id)")

if id == "NOTIFICATION_CUSTOM"{

switch response.actionIdentifier {
case "CUS_ACTION1":
// Handle action1

case "CUS_ACTION2":
// Handle action2

default:
break
}
}