skip to content

With UserNotifications, how do UNUserNotificationCenterDelegate's willPresent and didReceive callbacks handle a concert reminder in the foreground and its action buttons?

level: middleimportance: must knowfreq 70%

answer

  1. foreground arrival versus a person's response
  2. weak delegate, set before launch finishes
  3. banner and list replaced alert in iOS 14
  4. actionIdentifier and the default action
  5. categories registered once at launch

basics

~10 s

userNotificationCenter(:willPresent:withCompletionHandler:) runs while the app is in the foreground and returns options such as .banner, .list and .sound; userNotificationCenter(:didReceive:withCompletionHandler:) runs when the person taps or picks an action, and switches on actionIdentifier.

solid answer

~40 s

I assign an object the app keeps alive to `UNUserNotificationCenter.current().delegate` in `application(_:willFinishLaunchingWithOptions:)` or `didFinishLaunchingWithOptions`, because the property is weak and the delegate must be set before launch finishes. When a reminder arrives in the foreground, the center calls `userNotificationCenter(_:willPresent:withCompletionHandler:)`; if the delegate doesn't implement it or never calls the handler, nothing is shown. I return `[.banner, .list, .sound]` (iOS 14's replacements for the deprecated `.alert`) or `[]` when the screen already shows the update. The Show ticket and Remind me later buttons come from a `UNNotificationCategory` of `UNNotificationAction`s, registered once at launch with `setNotificationCategories(_:)` and matched by `categoryIdentifier`. Every response then reaches `userNotificationCenter(_:didReceive:withCompletionHandler:)`, where I switch on `actionIdentifier`, treat `UNNotificationDefaultActionIdentifier` as a plain tap, and call the completion handler when done.

code

swift · 38 lines
swift
import UIKit
import UserNotifications

final class ReminderHandler: NSObject, UNUserNotificationCenterDelegate {
    static let shared = ReminderHandler()  // owned here: the center's delegate is weak

    func registerCategories() {
        let show = UNNotificationAction(identifier: "SHOW_TICKET", title: "Show ticket", options: [.foreground])
        let later = UNNotificationAction(identifier: "REMIND_LATER", title: "Remind me later", options: [])
        let doors = UNNotificationCategory(identifier: "DOORS_REMINDER", actions: [show, later],
                                           intentIdentifiers: [])
        UNUserNotificationCenter.current().setNotificationCategories([doors])  // the full set, once
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
        [.banner, .list, .sound]  // foreground only
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse) async {
        let showID = response.notification.request.content.userInfo["showID"] as? String ?? ""
        switch response.actionIdentifier {
        case "SHOW_TICKET", UNNotificationDefaultActionIdentifier: print("open ticket", showID)
        case "REMIND_LATER": print("schedule a new reminder", showID)
        default: break
        }
    }
}

final class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication,
                     willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UNUserNotificationCenter.current().delegate = ReminderHandler.shared  // before launch finishes
        ReminderHandler.shared.registerCategories()
        return true
    }
}

go deeper

for a junior

Know which callback runs for a tap and that the completion handler must always be called.

for a middle

Explain when willPresent runs versus didReceive, the iOS 14 banner and list options, and how categories registered at launch become action identifiers.

for a senior

Show the launch-time traps: a weak delegate, assignment after launch, categories overwritten by a second registration, and actions that need foreground or unlock options.

for a principal

Argue for one notification handler that owns delegate, categories and action identifiers, so features cannot register competing sets or miss launch-time responses.

## Two callbacks, two moments The **UNUserNotificationCenterDelegate** protocol is how an app hears about notifications that the system would otherwise handle alone. It has two callbacks that matter here, and they answer different questions: | Callback | When it runs | What the app gives back | |---|---|---| | `userNotificationCenter(_:willPresent:withCompletionHandler:)` | A notification arrives while the app is in the foreground | `UNNotificationPresentationOptions`: how, if at all, to still show it | | `userNotificationCenter(_:didReceive:withCompletionHandler:)` | The person responds: taps the notification, picks an action, or dismisses it when the category asks for that | Nothing; it calls the completion handler when done | Both also have async forms (`willPresent` returning the options, `didReceive` returning when finished). A notification that arrives in the foreground goes to `willPresent`; `didReceive` runs only after the person does something with a notification. ## Setting the delegate early and keeping it alive The center's `delegate` property is **weak**, so the object you assign must be owned elsewhere: an app-wide handler, the app delegate itself, or a long-lived coordinator. Apple's documentation also says the delegate must be assigned **before the app finishes launching**, in `application(_:willFinishLaunchingWithOptions:)` or `application(_:didFinishLaunchingWithOptions:)`. Apple warns that a delegate assigned after those methods, for example in a view controller's `viewDidLoad()`, might miss incoming notifications, and a tap that launches the app is answered during that launch. A SwiftUI app reaches the same app-delegate methods through its delegate adaptor, which is covered with SwiftUI's app life cycle. ## Presentation options in the foreground When a reminder fires while the fan is looking at the app, the center asks `willPresent`. The header is explicit: if the method is not implemented or its handler is not called in time, the notification is not presented. The options are: - `.banner` and `.list` (iOS 14): show a banner, and keep the entry in Notification Center. - `.sound` and `.badge`: play the sound, update the badge. - `[]`: present nothing, which is right when the screen already shows the same information. `.alert` still compiles but was deprecated in iOS 14 in favour of `.banner` plus `.list`. ## Categories and actions Buttons are never sent with the notification. The app declares them up front: 1. Create a `UNNotificationAction` for each button, with a unique identifier, a title and options: `.foreground` brings the app forward, `.authenticationRequired` requires an unlocked device, `.destructive` highlights it. 2. Group them in a `UNNotificationCategory` with its own identifier; the `.customDismissAction` option asks the system to report dismissals too. 3. Register every category at once with `setNotificationCategories(_:)` at launch. The call replaces whatever was registered before, so pass the full set each time. 4. Tag each notification: a local one through `content.categoryIdentifier`, a push through the `category` key in its `aps` dictionary. For a typed reply, a `UNTextInputNotificationAction` adds a text field with its own button title and placeholder, and the response arrives as a `UNTextInputNotificationResponse` whose `userText` holds what the person typed; a concert app could use one for a question to the venue. Because responses can arrive while the device is locked, Apple warns that files protected with complete data protection may be unreadable at that moment. ## Handling the response `didReceive` gets a `UNNotificationResponse`. Its `notification.request.content.userInfo` carries the app's own keys, and `actionIdentifier` says what happened: - One of your action identifiers, such as `SHOW_TICKET` or `REMIND_LATER`. - `UNNotificationDefaultActionIdentifier` when the person opened the app from the notification. - `UNNotificationDismissActionIdentifier` when they dismissed it, only for categories with `.customDismissAction`. Action identifiers must be unique across the whole app, because the identifier is the only thing that tells two actions apart, even in different categories. An action without `.foreground` is handled with the app launched in the background, so Remind me later can simply add a new request; Show ticket needs `.foreground` to open a screen. Turning the tap into a navigation path is a SwiftUI navigation subject; this callback's job is to read the identifier and data and hand them on. Always call the completion handler when the work is done. ## What reviewers catch - A delegate stored in a local variable, so the weak property is `nil` by the time a notification arrives. - `willPresent` missing, so foreground reminders silently vanish. - Categories registered in two places, each call wiping the other's set. - A `switch` on `actionIdentifier` with no case for the default action, so a plain tap does nothing.

  • Why does dismissing the reminder never reach didReceive?
    Dismissals are reported only for categories created with the `.customDismissAction` option. Add it to the category, and `didReceive` then gets `UNNotificationDismissActionIdentifier` when the person clears the notification, which is where an app could, for example, stop a follow-up reminder.
  • What changes if the Show ticket action lacks the .foreground option?
    Without `.foreground` the system handles the action with the app launched in the background, so no screen opens and the fan sees nothing happen. Show ticket needs `.foreground`; Remind me later can stay in the background because it only adds a new request. If showing the ticket should require an unlocked device, add `.authenticationRequired` too.
  • Two categories both define an action with the identifier OPEN; what goes wrong?
    In `didReceive` the identifier is the only way to tell actions apart, and Apple requires every action identifier to be unique even across categories. Two OPEN actions arrive as the same string, so the app cannot know which was meant without extra checks; give each action its own identifier.

  • If the delegate skips willPresent, foreground notifications still appear as banners.
  • Setting the delegate in the first view controller's viewDidLoad is early enough.
  • The .alert presentation option is the current way to show a foreground banner.
  • A push can carry its own button definitions in the payload.
  • Calling setNotificationCategories again adds to the categories already registered.
  • A local variable can hold the delegate, because the center retains it.

Assumes the iOS 27 SDK on an iOS 17 baseline; .banner and .list arrived in iOS 14, when the .alert presentation option was deprecated.