Popular Searches
Popular Course Categories
Popular Courses

Managing Notification Permissions, Categories, and Actions

Managing Notification Permissions, Categories, and Actions

Background Tasks, Push Notifications, and App Services

Managing Notification Permissions, Categories, and Actions in iOS

Course: iOS App Development

Topic: Managing Notification Permissions, Categories, and Actions

Course Link: iOS Training – JustAcademy

Demo Link: Register for Course Demo

Website: JustAcademy


1. Introduction to iOS Notifications

Notifications are an important part of modern iOS applications. They allow apps to communicate useful information to users even when the application is not actively running or visible on the screen. Notifications can remind users about scheduled activities, announce new messages, provide order updates, display important alerts, and encourage users to return to an application.

Apple provides the UserNotifications framework to manage local notifications, remote push notifications, notification permissions, notification categories, custom actions, and notification responses.

Developers must request the appropriate authorization before displaying user-facing notifications. They should also respect notification preferences and provide meaningful actions that allow users to respond directly from the notification interface.

Examples of notification usage

  • A messaging application notifying users about new messages.
  • A shopping application displaying order and delivery updates.
  • A task management application reminding users about deadlines.
  • A banking application displaying transaction alerts.
  • A fitness application reminding users about scheduled workouts.
  • A calendar application providing meeting reminders.

2. Understanding the UserNotifications Framework

The UserNotifications framework provides APIs for creating, scheduling, delivering, and managing notifications. It also supports custom notification categories and actions.

Important classes and protocols

API Purpose
UNUserNotificationCenter Central object for managing notification authorization, scheduling, and responses.
UNNotificationSettings Provides the current notification authorization and presentation settings.
UNMutableNotificationContent Creates and modifies notification content.
UNNotificationRequest Represents a notification request submitted to the system.
UNNotificationTrigger Defines when a notification should be delivered.
UNNotificationCategory Defines a notification type and its available actions.
UNNotificationAction Defines a button or action displayed in a notification.
UNTextInputNotificationAction Creates an action that accepts text input.
UNNotificationResponse Contains information about the user's interaction with a notification.
UNUserNotificationCenterDelegate Receives callbacks for notification delivery and user interactions.

3. Types of iOS Notifications

iOS applications mainly use local notifications and remote push notifications. Both types can display alerts, play sounds, and update app icon badges when the relevant permissions and settings allow them.

3.1 Local Notifications

Local notifications are created and scheduled directly by an application on the device. The application defines the notification content and the condition that triggers delivery.

Examples include:

  • Daily reminders.
  • Medication or appointment reminders.
  • Scheduled task notifications.
  • Event countdown notifications.
  • Offline reminders created by the user.

3.2 Remote Push Notifications

Remote notifications are generated by a server and delivered through Apple Push Notification service (APNs). The application server sends a notification request to APNs, which routes it to the user's device.

Examples include:

  • New chat messages.
  • Payment confirmations.
  • Order status updates.
  • Breaking news alerts.
  • Social media activity updates.
Feature Local Notification Remote Notification
Created by Application on the device Remote application server
Delivery mechanism iOS notification system Apple Push Notification service
Internet requirement Not required for scheduling Generally requires network connectivity for delivery
Common usage Reminders and scheduled events Messages and server updates
Trigger Time or supported location condition Server sends a push request through APNs

4. Understanding Notification Permissions

Notification permissions control whether an application can interact with users through alerts, sounds, badges, and other notification-related features.

iOS requires an application to request authorization before using user-facing notification interactions. Developers should explain the benefit of notifications before presenting the system permission prompt.

Notification permission options

Permission Option Description
alert Requests permission to display notification alerts.
sound Requests permission to play notification sounds.
badge Requests permission to update the app icon badge.
provisional Requests provisional authorization for quiet notification delivery without the standard initial permission alert.
criticalAlert Requests access to critical alerts, which require a special entitlement from Apple.
announcement Requests authorization for supported notification announcement experiences.

Request only the permission options that match the application's actual functionality. Some options have additional entitlement or platform requirements.

5. Requesting Notification Permission

The UNUserNotificationCenter class provides the requestAuthorization(options:completionHandler:) method for requesting notification authorization.

Step 1: Import the framework

import UserNotifications

Step 2: Request authorization

import UserNotifications

func requestNotificationPermission() {
    let center = UNUserNotificationCenter.current()

    center.requestAuthorization(
        options: [.alert, .sound, .badge]
    ) { granted, error in

        if let error = error {
            print("Permission error: \(error.localizedDescription)")
            return
        }

        if granted {
            print("Notification permission granted")
        } else {
            print("Notification permission denied")
        }
    }
}

Explanation

  1. Import the UserNotifications framework.
  2. Access the shared notification center.
  3. Specify the required permission options.
  4. Call the authorization request method.
  5. Check the returned permission result.
  6. Enable or disable notification-related features according to the result.

Important: The system normally displays its permission prompt the first time an app requests authorization. Calling the request method again does not repeatedly display the same prompt after the user has made a decision.

6. Best Time to Request Notification Permission

Permission requests should be presented when users understand why notifications are useful. Automatically requesting permission immediately after the first launch may lead users to deny access because they do not yet understand the application's notification features.

Recommended permission request flow

  1. The user opens the application.
  2. The application introduces a feature that uses notifications.
  3. The application explains the benefits of enabling notifications.
  4. The user chooses to enable notifications.
  5. The application requests system authorization.
  6. The application checks the authorization result.
  7. The application adjusts its notification functionality accordingly.

Example: Request permission after a user schedules a reminder

func enableReminderNotifications() {
    let center = UNUserNotificationCenter.current()

    center.requestAuthorization(
        options: [.alert, .sound, .badge]
    ) { granted, error in

        DispatchQueue.main.async {
            if granted {
                print("Reminders can use notifications")
            } else {
                print("Reminders will remain available without alerts")
            }
        }
    }
}

7. Understanding Notification Authorization Status

The UNAuthorizationStatus enumeration describes the application's current notification authorization state.

Status Meaning Recommended Handling
notDetermined The user has not yet made an authorization decision. Explain the feature and request permission when appropriate.
denied The user has denied notification authorization. Respect the decision and optionally guide the user to Settings.
authorized The user has authorized notifications. Check individual settings before choosing presentation behavior.
provisional The application has provisional notification authorization. Use quiet delivery and explain how the user can manage notification preferences.
ephemeral Temporary notification authorization for supported app experiences, such as certain App Clip scenarios. Handle according to the temporary authorization and platform rules.

Checking the current authorization status

import UserNotifications

func checkNotificationAuthorization() {
    let center = UNUserNotificationCenter.current()

    center.getNotificationSettings { settings in

        switch settings.authorizationStatus {

        case .notDetermined:
            print("Permission not requested")

        case .denied:
            print("Notifications are denied")

        case .authorized:
            print("Notifications are authorized")

        case .provisional:
            print("Provisional notification access")

        case .ephemeral:
            print("Temporary notification access")

        @unknown default:
            print("Unknown authorization status")
        }
    }
}

8. Understanding Individual Notification Settings

Receiving notification authorization does not necessarily mean every notification feature is enabled. Users can separately control alerts, sounds, badges, Lock Screen visibility, Notification Center delivery, previews, and other supported settings.

The UNNotificationSettings object provides information about these preferences.

Important notification setting properties

Property Purpose
authorizationStatus Returns the overall authorization status.
alertSetting Indicates whether alerts are enabled.
soundSetting Indicates whether notification sounds are enabled.
badgeSetting Indicates whether badge updates are enabled.
lockScreenSetting Indicates whether notifications can appear on the Lock Screen.
notificationCenterSetting Indicates whether notifications can appear in Notification Center.
showPreviewsSetting Indicates how notification previews are displayed.
timeSensitiveSetting Indicates whether time-sensitive notifications are allowed.
scheduledDeliverySetting Indicates whether scheduled delivery is enabled.

Example: Checking alert, sound, and badge settings

func inspectNotificationSettings() {
    UNUserNotificationCenter.current()
        .getNotificationSettings { settings in

            print("Authorization: \(settings.authorizationStatus)")

            print("Alerts: \(settings.alertSetting)")
            print("Sounds: \(settings.soundSetting)")
            print("Badges: \(settings.badgeSetting)")

            print("Lock Screen: \(settings.lockScreenSetting)")
            print("Notification Center: \(settings.notificationCenterSetting)")
        }
}

9. Handling Denied Notification Permissions

Users can deny notification authorization or disable specific notification features from iOS Settings. Applications should respect these choices and continue providing useful functionality wherever possible.

Recommended handling

  • Check the authorization status before scheduling user-facing notifications.
  • Do not repeatedly request permission after it has been denied.
  • Explain which features require notifications.
  • Provide an optional button that opens the application's Settings page.
  • Allow users to continue using features that do not depend on notifications.

Opening application settings

import UIKit

func openAppSettings() {
    guard let settingsURL = URL(
        string: UIApplication.openSettingsURLString
    ) else {
        return
    }

    UIApplication.shared.open(settingsURL)
}

The user must enable notification access manually in Settings. The application cannot silently change the system authorization decision.

10. Understanding Provisional Notification Authorization

Provisional authorization allows an application to deliver notifications quietly before the user makes a full notification permission decision. It can be useful when an application wants users to experience notifications before deciding whether they want more prominent delivery.

Characteristics

  • The initial provisional request does not show the standard authorization prompt.
  • Notifications are delivered quietly.
  • They do not interrupt users with standard banners or notification sounds.
  • Users can choose to keep or turn off notifications through the system interface.
  • The application should check the current authorization status before scheduling notifications.

Example: Requesting provisional authorization

func requestProvisionalAuthorization() async {
    let center = UNUserNotificationCenter.current()

    do {
        let granted = try await center.requestAuthorization(
            options: [.alert, .sound, .badge, .provisional]
        )

        print("Provisional request result: \(granted)")

    } catch {
        print("Authorization error: \(error.localizedDescription)")
    }
}

11. Introduction to Notification Categories

Notification categories define different types of notifications supported by an application. Each category can contain custom actions that appear as buttons when the system displays a notification.

For example, a task management application might define categories for task reminders, meeting reminders, and deadline alerts. Each category can provide actions relevant to that notification type.

Examples of notification categories

Category Purpose Possible Actions
MESSAGE New message notification Reply, Mark as Read
MEETING Meeting invitation Accept, Decline
TASK_REMINDER Task reminder Complete, Snooze
ORDER_UPDATE Shopping order update Track Order, View Details
EVENT_REMINDER Upcoming event notification View Event, Remind Later

12. Understanding UNNotificationCategory

The UNNotificationCategory class represents a notification type and the actions associated with it.

Important parameters

Parameter Description
identifier Unique identifier used to recognize the category.
actions Array of notification actions associated with the category.
intentIdentifiers Identifiers for supported SiriKit intents associated with the category.
hiddenPreviewsBodyPlaceholder Placeholder text used when notification previews are hidden.
options Additional category behavior options.

The category identifier must match the identifier assigned to the notification content or remote notification payload. Otherwise, the system cannot associate the notification with the registered category actions.

13. Understanding UNNotificationAction

UNNotificationAction defines an interactive button displayed in a notification. Users can select an action without necessarily opening the application interface.

Common notification actions

  • Accept an invitation.
  • Decline an invitation.
  • Mark a message as read.
  • Complete a task.
  • Open a relevant application screen.
  • Delete or dismiss an item when appropriate.

Action options

Option Description
.foreground Requests that the application be brought to the foreground when the action is selected.
.destructive Marks an action as destructive, allowing the system to visually distinguish it.
.authenticationRequired Requires the user to unlock the device before performing the action.

14. Creating Custom Notification Actions

Developers can create actions using UNNotificationAction and attach them to a notification category.

Example: Creating Accept and Decline actions

import UserNotifications

func registerMeetingNotificationCategory() {

    let acceptAction = UNNotificationAction(
        identifier: "ACCEPT_ACTION",
        title: "Accept",
        options: []
    )

    let declineAction = UNNotificationAction(
        identifier: "DECLINE_ACTION",
        title: "Decline",
        options: [.destructive]
    )

    let meetingCategory = UNNotificationCategory(
        identifier: "MEETING_CATEGORY",
        actions: [acceptAction, declineAction],
        intentIdentifiers: [],
        options: []
    )

    UNUserNotificationCenter.current()
        .setNotificationCategories([meetingCategory])
}

Explanation

  1. Create the first action using UNNotificationAction.
  2. Create the second action with its own unique identifier.
  3. Create a notification category.
  4. Attach the actions to the category.
  5. Register the category with the notification center.
  6. Assign the category identifier to notifications that should display these actions.

15. Registering Notification Categories at App Launch

Notification categories should be registered early in the application lifecycle, before the application needs to display notifications using those categories.

Registering categories with setNotificationCategories(_:) replaces the previously registered category set. Therefore, include all categories that the application supports in the registration call.

Example: Registering multiple categories

func registerAllNotificationCategories() {

    let replyAction = UNNotificationAction(
        identifier: "REPLY_ACTION",
        title: "Reply",
        options: [.foreground]
    )

    let markReadAction = UNNotificationAction(
        identifier: "MARK_READ_ACTION",
        title: "Mark as Read",
        options: []
    )

    let messageCategory = UNNotificationCategory(
        identifier: "MESSAGE_CATEGORY",
        actions: [replyAction, markReadAction],
        intentIdentifiers: [],
        options: []
    )

    let acceptAction = UNNotificationAction(
        identifier: "ACCEPT_MEETING",
        title: "Accept",
        options: []
    )

    let declineAction = UNNotificationAction(
        identifier: "DECLINE_MEETING",
        title: "Decline",
        options: [.destructive]
    )

    let meetingCategory = UNNotificationCategory(
        identifier: "MEETING_CATEGORY",
        actions: [acceptAction, declineAction],
        intentIdentifiers: [],
        options: []
    )

    UNUserNotificationCenter.current()
        .setNotificationCategories([
            messageCategory,
            meetingCategory
        ])
}

16. Understanding Text Input Notification Actions

Some notifications require users to enter a response instead of selecting a predefined button. For this purpose, iOS provides UNTextInputNotificationAction.

For example, a messaging application can display a notification with a Reply action. When the user selects it, the system displays a text input interface where the user can type a response.

Creating a text input action

let replyAction = UNTextInputNotificationAction(
    identifier: "TEXT_REPLY_ACTION",
    title: "Reply",
    options: [.authenticationRequired],
    textInputButtonTitle: "Send",
    textInputPlaceholder: "Type your message..."
)

let messageCategory = UNNotificationCategory(
    identifier: "CHAT_CATEGORY",
    actions: [replyAction],
    intentIdentifiers: [],
    options: []
)

UNUserNotificationCenter.current()
    .setNotificationCategories([messageCategory])

Advantages of text input actions

  • Users can respond without opening the full application.
  • Messaging workflows become faster.
  • Simple replies can be handled directly from notifications.
  • Applications can provide context-specific text input.

17. Assigning a Category to a Local Notification

Registering a category alone does not display its actions. The notification content must contain the matching category identifier.

Example: Scheduling a meeting notification

import UserNotifications

func scheduleMeetingNotification() {

    let content = UNMutableNotificationContent()

    content.title = "Meeting Reminder"
    content.body = "Your project meeting starts soon."
    content.sound = .default
    content.categoryIdentifier = "MEETING_CATEGORY"

    let trigger = UNTimeIntervalNotificationTrigger(
        timeInterval: 10,
        repeats: false
    )

    let request = UNNotificationRequest(
        identifier: "meeting_reminder_001",
        content: content,
        trigger: trigger
    )

    UNUserNotificationCenter.current()
        .add(request) { error in

            if let error = error {
                print("Scheduling error: \(error.localizedDescription)")
            } else {
                print("Meeting notification scheduled")
            }
        }
}

When the notification is delivered, the system uses the category identifier to find the registered actions and display the appropriate buttons.

18. Handling Notification Actions with UNUserNotificationCenterDelegate

The UNUserNotificationCenterDelegate protocol allows the application to respond when users interact with notifications. It supports handling action selections, notification taps, and foreground notification presentation.

Important delegate methods

Delegate Method Purpose
userNotificationCenter(_:willPresent:withCompletionHandler:) Determines how a notification is presented while the app is in the foreground.
userNotificationCenter(_:didReceive:withCompletionHandler:) Handles user interactions with delivered notifications and their actions.

Example: Implementing the notification delegate

import UIKit
import UserNotifications

class AppDelegate: NSObject,
                   UIApplicationDelegate,
                   UNUserNotificationCenterDelegate {

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions:
            [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {

        let center = UNUserNotificationCenter.current()

        center.delegate = self

        registerAllNotificationCategories()

        return true
    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler:
            @escaping (UNNotificationPresentationOptions) -> Void
    ) {

        completionHandler([.banner, .sound, .badge])
    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {

        let actionIdentifier = response.actionIdentifier

        switch actionIdentifier {

        case "ACCEPT_MEETING":
            print("Meeting accepted")

        case "DECLINE_MEETING":
            print("Meeting declined")

        case "REPLY_ACTION":
            print("Reply action selected")

        case UNNotificationDefaultActionIdentifier:
            print("User opened the notification")

        case UNNotificationDismissActionIdentifier:
            print("User dismissed the notification")

        default:
            print("Other notification action selected")
        }

        completionHandler()
    }
}

Important: Assign the notification center delegate early during application setup. Also, call the supplied completion handler after handling each callback.

19. Handling Text Input Responses

When a user selects a text input notification action, the response can be converted to UNTextInputNotificationResponse to retrieve the entered text.

Example: Reading a quick reply

func handleNotificationResponse(
    _ response: UNNotificationResponse
) {

    if response.actionIdentifier == "TEXT_REPLY_ACTION" {

        guard let textResponse =
            response as? UNTextInputNotificationResponse else {
            return
        }

        let replyText = textResponse.userText

        print("User reply: \(replyText)")

        // Send the reply through your messaging service.
    }
}

In a production messaging application, validate the text, identify the correct conversation, handle network errors, and store the response safely. Do not assume that the network request will always succeed immediately.

20. Understanding Foreground Notification Presentation

When a notification arrives while the application is in the foreground, the system calls the willPresent delegate method. The application can decide whether the notification should display a banner, play a sound, update a badge, or remain silent.

Presentation options

Option Purpose
.banner Displays a notification banner.
.list Allows the notification to appear in the notification list.
.sound Plays the notification sound when allowed.
.badge Updates the application badge according to the notification content.

Example: Presenting a notification while the app is open

func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler:
        @escaping (UNNotificationPresentationOptions) -> Void
) {

    completionHandler([.banner, .list, .sound])
}

The system still enforces the user's notification settings. Requesting a presentation option does not override disabled alerts, sounds, or other preferences.

21. Managing Notification Categories in Remote Push Notifications

Remote notifications can also display custom actions. The notification payload must contain the category identifier that matches a category registered by the application.

Example remote notification payload

{
    "aps": {
        "alert": {
            "title": "New Meeting Invitation",
            "body": "Would you like to attend the project meeting?"
        },
        "sound": "default",
        "category": "MEETING_CATEGORY"
    },
    "meeting_id": "meeting_101",
    "organizer": "Project Manager"
}

How it works

  1. The application registers the meeting notification category.
  2. The server creates a push notification payload.
  3. The payload includes the matching category identifier.
  4. APNs delivers the notification to the device.
  5. iOS identifies the registered category.
  6. The system displays the available actions.
  7. The user selects an action.
  8. The application receives the selected action through its notification delegate.

For remote notifications, the category identifier in the APNs payload must match the registered category identifier exactly.

22. Managing Notification Badge Counts

A badge is a small visual indicator displayed on an application's icon. It commonly represents the number of unread messages, pending tasks, or outstanding notifications.

Setting a badge through notification content

let content = UNMutableNotificationContent()

content.title = "New Messages"
content.body = "You have 5 unread messages."
content.badge = 5

Clearing the badge count

import UIKit

func clearAppBadge() {
    UNUserNotificationCenter.current()
        .setBadgeCount(0) { error in

            if let error = error {
                print("Unable to clear badge: \(error)")
            } else {
                print("Badge cleared")
            }
        }
}

Badge behavior depends on user authorization and settings. Keep badge values synchronized with the application's actual unread or pending item count.

23. Removing Pending and Delivered Notifications

Applications should manage notifications when users complete tasks, cancel appointments, or change reminder preferences.

Removing a specific pending notification

func cancelMeetingReminder() {
    UNUserNotificationCenter.current()
        .removePendingNotificationRequests(
            withIdentifiers: ["meeting_reminder_001"]
        )
}

Removing all pending notifications

func removeAllScheduledNotifications() {
    UNUserNotificationCenter.current()
        .removeAllPendingNotificationRequests()
}

Removing delivered notifications

func removeDeliveredNotifications() {
    UNUserNotificationCenter.current()
        .removeAllDeliveredNotifications()
}
Method Effect
removePendingNotificationRequests(withIdentifiers:) Removes selected scheduled notifications.
removeAllPendingNotificationRequests() Removes all pending notification requests.
removeDeliveredNotifications(withIdentifiers:) Removes selected notifications already delivered.
removeAllDeliveredNotifications() Removes all delivered notifications from the notification center.

24. Notification Privacy and Security

Notifications may display personal information on the Lock Screen or other system interfaces. Developers should avoid exposing confidential data unnecessarily.

Security best practices

  • Avoid including passwords, authentication tokens, or sensitive financial details in notification text.
  • Use generic notification previews when privacy is important.
  • Require authentication for sensitive notification actions when appropriate.
  • Validate action identifiers and notification payload data.
  • Verify user authorization before performing sensitive operations.
  • Protect message and account information in local storage.
  • Use secure server communication for remote notification workflows.

Using authentication-required actions

let secureAction = UNNotificationAction(
    identifier: "OPEN_SECURE_RECORD",
    title: "View Details",
    options: [.foreground, .authenticationRequired]
)

Authentication-related action options help protect sensitive interactions. They do not replace application-level authentication and authorization checks.

25. Notification Delivery and System Restrictions

Even when an application has notification authorization, delivery and presentation are influenced by iOS settings and system behavior.

Factors that can affect notification presentation

  • The user's notification authorization.
  • Individual alert, sound, and badge settings.
  • Focus modes and notification filtering.
  • Scheduled Summary settings.
  • Device connectivity for remote notifications.
  • Notification relevance and system policies.
  • Application notification scheduling and payload configuration.

Local and remote notification delivery should not be treated as an absolute real-time guarantee. Applications should provide a reliable way to view current information inside the app.

26. Common Notification Errors and Troubleshooting

Problem Possible Cause Solution
Permission prompt does not appear The user already made an authorization decision. Check notification settings and guide the user to Settings when appropriate.
Notification is not displayed Authorization is denied or alert settings are disabled. Inspect UNNotificationSettings.
Action buttons are missing Category identifier is missing or incorrect. Register the category and assign its exact identifier to the notification.
Action does not work Action identifier is not handled by the delegate. Implement the didReceive response method.
Notification is silent Sound permission or sound settings are disabled. Check sound authorization and user preferences.
Badge is not updated Badge permission is disabled or the badge value is incorrect. Check badge settings and set the correct count.
Foreground notification is not visible Foreground presentation options were not provided. Implement the willPresent delegate method.
Text reply is unavailable The response is not being cast to the text input response type. Use UNTextInputNotificationResponse.
Remote notification actions are missing The APNs payload category does not match a registered category. Verify the category identifier in the payload.
Notifications arrive inconsistently Network, Focus, system delivery, or user settings affect delivery. Test delivery conditions and avoid relying on guaranteed timing.

27. Testing Notifications in Xcode

Testing notification permissions, categories, and actions is essential for verifying that an application behaves correctly in different authorization states.

Testing checklist

  • Install the app on a real device or supported simulator.
  • Test the first-time permission request.
  • Test when notification permission is granted.
  • Test when notification permission is denied.
  • Change alert, sound, and badge settings independently.
  • Test provisional authorization when supported.
  • Schedule a local notification and verify its delivery.
  • Verify that the correct category actions are displayed.
  • Test every custom action.
  • Test text input notification responses.
  • Test notification behavior while the app is in the foreground.
  • Test notification behavior while the app is in the background.
  • Test remote notifications using APNs and the appropriate development configuration.
  • Verify that the app handles invalid payload data safely.

28. Practical Project: Task Reminder Application

Create a task reminder application that allows users to schedule reminders and respond to them through notification actions.

Project requirements

  • Request notification permission when a user enables reminders.
  • Display the current authorization status.
  • Register a TASK_REMINDER notification category.
  • Create Complete and Snooze actions.
  • Schedule a local notification for a selected date and time.
  • Handle the Complete action by updating the task status.
  • Handle the Snooze action by scheduling another reminder.
  • Allow users to cancel pending reminders.
  • Display an appropriate message when notification permission is denied.

Example: Creating Complete and Snooze actions

func registerTaskReminderCategory() {

    let completeAction = UNNotificationAction(
        identifier: "COMPLETE_TASK",
        title: "Complete",
        options: []
    )

    let snoozeAction = UNNotificationAction(
        identifier: "SNOOZE_TASK",
        title: "Snooze",
        options: []
    )

    let category = UNNotificationCategory(
        identifier: "TASK_REMINDER",
        actions: [completeAction, snoozeAction],
        intentIdentifiers: [],
        options: []
    )

    UNUserNotificationCenter.current()
        .setNotificationCategories([category])
}

Example: Handling task actions

func handleTaskReminderAction(
    response: UNNotificationResponse
) {

    switch response.actionIdentifier {

    case "COMPLETE_TASK":
        print("Task marked as completed")
        // Update the task in persistent storage.

    case "SNOOZE_TASK":
        print("Task snoozed")
        // Schedule another reminder.

    default:
        print("Default notification interaction")
    }
}

This project demonstrates notification authorization, category registration, action creation, local notification scheduling, and response handling in one practical application.

29. Best Practices for Managing iOS Notifications

  • Request notification permission only when the user understands its purpose.
  • Request only the authorization options required by the application.
  • Check notification settings before choosing notification behavior.
  • Respect users who deny or disable notifications.
  • Register all notification categories early in the application lifecycle.
  • Use unique and meaningful category and action identifiers.
  • Match local notification and APNs category identifiers exactly.
  • Implement both foreground presentation and action-response handling.
  • Call notification completion handlers correctly.
  • Validate user input from text notification actions.
  • Keep notification content concise and useful.
  • Avoid exposing sensitive data in notification previews.
  • Remove outdated pending notifications when tasks are completed or changed.
  • Test notifications under different permission and device settings.

30. Interview Questions and Answers

Q1. What is the UserNotifications framework?

Answer: UserNotifications is Apple's framework for managing local and remote notifications, requesting authorization, registering categories, defining actions, and handling user interactions.

Q2. What is the difference between local and remote notifications?

Answer: Local notifications are scheduled by the application on the device, while remote notifications are generated by a server and delivered through APNs.

Q3. Which class is used to request notification permission?

Answer: The shared UNUserNotificationCenter instance provides the requestAuthorization method.

Q4. What is UNNotificationSettings?

Answer: It provides information about the current notification authorization status and individual settings such as alerts, sounds, and badges.

Q5. What is UNNotificationCategory?

Answer: It defines a notification type and the custom actions associated with that type.

Q6. What is UNNotificationAction?

Answer: It defines an interactive action button that users can select from a notification.

Q7. What is UNTextInputNotificationAction?

Answer: It creates a notification action that allows users to enter custom text, such as replying to a message.

Q8. What is the purpose of setNotificationCategories?

Answer: It registers the notification categories supported by the application. Each registration call replaces the previously registered category set.

Q9. How does iOS identify which actions to display?

Answer: iOS matches the category identifier in the notification content or remote payload with a registered UNNotificationCategory identifier.

Q10. Which delegate method handles notification action selection?

Answer: userNotificationCenter(_:didReceive:withCompletionHandler:) receives the user's notification response and action identifier.

Q11. Which delegate method controls foreground notification presentation?

Answer: userNotificationCenter(_:willPresent:withCompletionHandler:) determines how an incoming notification is presented while the app is in the foreground.

Q12. What is provisional notification authorization?

Answer: It allows an application to deliver notifications quietly before the user makes a full authorization decision.

Q13. How can an application guide users after notification permission is denied?

Answer: It can explain the notification-dependent feature and provide an optional link to the application's Settings page. It cannot change the user's permission decision automatically.

Q14. What is the purpose of UNNotificationResponse?

Answer: It contains information about the notification interaction, including the selected action identifier and the original notification.

Q15. Why should notification categories be registered at launch?

Answer: Early registration ensures that the system knows which notification types and actions the application supports when notifications arrive.

31. Quick Revision Checklist

  • Understand the purpose of the UserNotifications framework.
  • Differentiate local and remote notifications.
  • Know how to request notification authorization.
  • Understand notification authorization statuses.
  • Check individual alert, sound, and badge settings.
  • Understand denied and provisional authorization.
  • Know how to open application Settings.
  • Understand UNNotificationCategory.
  • Understand UNNotificationAction and its options.
  • Create text input notification actions.
  • Register categories at application launch.
  • Assign category identifiers to notification content.
  • Handle notification actions through the delegate.
  • Handle notifications received while the app is in the foreground.
  • Understand badge management and notification cleanup.
  • Test local and remote notification workflows.

32. Conclusion

Managing notification permissions, categories, and actions is an essential skill for iOS developers. The UserNotifications framework provides the tools required to request user authorization, inspect notification settings, create notification categories, define interactive actions, and handle user responses.

Developers should request permission at the right time, respect the user's notification preferences, and register meaningful notification categories. Custom actions such as Accept, Decline, Reply, Complete, and Snooze make applications more interactive and convenient. By implementing the appropriate delegate methods, validating notification responses, protecting private information, and testing different authorization states, developers can build reliable and user-friendly notification experiences.

33. Official Apple Documentation and Learning Resources


Explore iOS App Development Training: View iOS Training Course | Register for a Course Demo | Visit JustAcademy

Previous Next
whatsapp