How do I handle notification actions and categories in Swift?

In Swift, handling notification actions and categories is essential for creating enriched user experiences through push notifications. The process involves defining notification categories that group related actions, and then handling those actions when the user interacts with the notification. Below is an example that demonstrates how to implement notification actions and categories in a Swift application.

import UserNotifications // Step 1: Define notification actions let acceptAction = UNNotificationAction(identifier: "ACCEPT_ACTION", title: "Accept", options: [.foreground]) let declineAction = UNNotificationAction(identifier: "DECLINE_ACTION", title: "Decline", options: [.destructive]) // Step 2: Define a notification category let meetingInviteCategory = UNNotificationCategory(identifier: "MEETING_INVITE", actions: [acceptAction, declineAction], intentIdentifiers: [], options: []) // Step 3: Register the notification category UNUserNotificationCenter.current().setNotificationCategories([meetingInviteCategory]) // Step 4: Handling the notification response UNUserNotificationCenter.current().delegate = self func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { if response.notification.categoryIdentifier == "MEETING_INVITE" { switch response.actionIdentifier { case "ACCEPT_ACTION": print("User accepted the meeting invite.") case "DECLINE_ACTION": print("User declined the meeting invite.") default: break } } completionHandler() }

Swift Notification Actions Notification Categories User Notifications iOS Development