User notifications in iOS not only help keep users informed but can also be made interactive, allowing users to take actions directly from the notification. In this article, we’ll cover how to handle opening a notification by tapping, as well as adding interactive elements like buttons and text fields.
Handling Notification Taps
When a user taps on a notification, you can specify how the app responds by implementing a UNUserNotificationCenterDelegate
method in your NotificationDelegate
file.
@MainActor
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse
) async {
print("Notification tapped")
}
Adding Action Buttons to Notifications
Interactive notifications can contain buttons for quick actions, like marking a task as complete or snoozing a reminder. To do this, first you need to define the custom actions, add them to a UNNotificationCategory
, and register this category.
let completeAction = UNNotificationAction(
identifier: "COMPLETE_ACTION",
title: "Complete",
options: [.foreground]
)
let snoozeAction = UNNotificationAction(
identifier: "SNOOZE_ACTION",
title: "Snooze",
options: []
)
let category = UNNotificationCategory(
identifier: "TASK_CATEGORY",
actions: [completeAction, snoozeAction],
intentIdentifiers: [],
options: []
)
UNUserNotificationCenter.current().setNotificationCategories([category])
Then we'll add this category to our local or remote notifications, showing the actions we defined for that category.
Local notification
let content = UNMutableNotificationContent()
content.title = "Task Reminder"
content.body = "Don't forget to complete your task."
content.categoryIdentifier = "TASK_CATEGORY"
Remote notification
{
"aps": {
"alert": {
"title": "Task Reminder",
"body": "Don't forget to complete your task.",
},
"badge": 12,
"category": "TASK_CATEGORY"
}
}
When the user taps on an action, our existing delegate method will be triggered and we'll be able to check the action identifier.
@MainActor
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
switch response.actionIdentifier {
case "COMPLETE_ACTION":
print("User tapped Complete")
// Handle completion of task
case "SNOOZE_ACTION":
print("User tapped Snooze")
// Handle snoozing of task
default:
print("User tapped notification")
}
}
Be the first to comment