With UserNotifications, how does an iOS app ask for notification permission and schedule a one-off local reminder two hours before a concert's doors open?
answer
- the shared center, then one prompt
- options: alert, sound, badge
- content, trigger, request with an identifier
- calendar components or seconds from now
- same identifier replaces the pending one
basics
~10 sCall requestAuthorization(options:) on UNUserNotificationCenter.current() with .alert, .sound and .badge, then build UNMutableNotificationContent, a UNCalendarNotificationTrigger for two hours before doors open, and add a UNNotificationRequest with a stable identifier.
solid answer
~40 sI take `UNUserNotificationCenter.current()` and call `requestAuthorization(options: [.alert, .sound, .badge])`; the system prompts only the first time and reports the stored answer afterwards, so I ask when the fan saves a ticket, not at launch. If it returns `true`, I fill a `UNMutableNotificationContent` (title, body, sound, the show ID in `userInfo`), compute the moment two hours before doors open and pass its year-to-minute components to `UNCalendarNotificationTrigger(dateMatching:repeats:)` with `repeats: false`; a `UNTimeIntervalNotificationTrigger` with the seconds until then also works. The `UNNotificationRequest` gets a stable identifier such as `doors-<showID>`, because adding a request with an identifier that is already pending replaces it, which is how a changed doors time is rescheduled; `removePendingNotificationRequests(withIdentifiers:)` cancels it. People can change permission at any time, so later scheduling reads `notificationSettings()` first.
code
swift · 22 linesimport UserNotifications
func scheduleDoorsReminder(showID: String, doorsOpen: Date) async throws {
let center = UNUserNotificationCenter.current()
guard try await center.requestAuthorization(options: [.alert, .sound, .badge]) else { return }
let content = UNMutableNotificationContent()
content.title = "Doors open in two hours"
content.body = "Your ticket is ready in the app."
content.sound = .default
content.userInfo = ["showID": showID]
let fireDate = doorsOpen.addingTimeInterval(-2 * 60 * 60)
let parts = Calendar.current.dateComponents(
[.year, .month, .day, .hour, .minute], from: fireDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: parts, repeats: false)
// Same identifier again replaces this request instead of adding a second one.
let request = UNNotificationRequest(
identifier: "doors-\(showID)", content: content, trigger: trigger)
try await center.add(request)
}go deeper
Recall the three pieces in order: requestAuthorization with alert, sound and badge, the content object, and a request that pairs a trigger with an identifier.
Explain why the identifier is stable, what replacement and cancellation do, and why the prompt appears only once while settings must be read again later.
Show judgment about which trigger fits a fixed moment versus a repeating clock time, the 60-second floor for repeating intervals, and reading settings before every later schedule.
Frame the trade-off between asking early and asking in context, and when provisional delivery is worth its quieter first impression for a reminder feature.
## What a local notification needs A **local notification** is one the app schedules on the device itself, with no server and no Apple Push Notification service (APNs) involved. With the UserNotifications framework it always takes the same three pieces, all handed to the app's shared `UNUserNotificationCenter`, which you get from `UNUserNotificationCenter.current()`: - **Permission** from the person to alert, play sounds or badge the icon. - **Content**: a `UNMutableNotificationContent` with the title, body, sound and any custom data in `userInfo`. - **A request**: a `UNNotificationRequest` that pairs the content with a **trigger** (the condition that fires it) and an **identifier** (the name you use to replace or cancel it). ## Asking for permission `requestAuthorization(options:completionHandler:)`, or its async form `requestAuthorization(options:) async throws -> Bool`, asks for the interaction types the app will use. The first call shows the system prompt; the system stores the answer, and every later call returns that stored answer without prompting again. Apple's documentation asks you to request only the options you plan to use and to ask in a context that explains why, for example right after the fan saves a ticket. | Option | What it asks for | Note | |---|---|---| | `.alert`, `.sound`, `.badge` | Banners and list entries, sounds, the icon badge | The everyday set | | `.provisional` | Quiet trial delivery with no prompt | iOS 12; status reads `.provisional` | | `.criticalAlert` | Alerts that ignore the mute switch | iOS 12; needs an entitlement Apple approves | | `.providesAppNotificationSettings` | A link from Settings to the app's own notification screen | iOS 12 | `UNAuthorizationOptions.timeSensitive` also exists but the SDK has marked it deprecated since iOS 15: time-sensitive delivery comes from an entitlement plus the content's `interruptionLevel`, not from an authorization option. ## Building the request The trigger decides when the system delivers the notification: | Trigger | Fires | Typical use | |---|---|---| | `UNTimeIntervalNotificationTrigger` | After a number of seconds | Timers, "in two hours" | | `UNCalendarNotificationTrigger` | When date components match | A clock time, or a repeating daily or weekly time | | `UNLocationNotificationTrigger` | On entering or leaving a region | Needs Core Location when-in-use permission | For a doors-open reminder the app knows an exact moment, so it can subtract two hours and either pass the seconds until then to a time-interval trigger, or pass the year, month, day, hour and minute to a calendar trigger with `repeats: false`. Leaving out the year, month and day would make the components match the next time that hour and minute come round, and with `repeats: true` every day after, which is how you build a daily reminder, not a one-off. A repeating time-interval trigger must use an interval of 60 seconds or more, and a repeating request keeps firing until you remove it. The request is then added with `add(_:)` (async) or `add(_:withCompletionHandler:)`. A request without a trigger is delivered right away. ## Replacing, cancelling and checking later The identifier is what makes the reminder manageable: 1. **Replace**: adding a request whose identifier matches a pending one replaces the pending request, so `doors-<showID>` can be re-added when the venue moves doors open. 2. **Cancel**: `removePendingNotificationRequests(withIdentifiers:)` removes it when the fan sells the ticket; `removeAllPendingNotificationRequests()` clears everything. 3. **Inspect**: `getPendingNotificationRequests(completionHandler:)` lists what is still waiting, and the system limits how many pending requests one app may have. Permission is not a one-time fact. People change it in Settings, so before scheduling a later reminder the app calls `getNotificationSettings(completionHandler:)` (async: `notificationSettings()`) and checks `authorizationStatus` and, if it matters, `alertSetting`: ```swift let settings = await UNUserNotificationCenter.current().notificationSettings() guard settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional else { return } ``` ## Mistakes that show up in review - **Asking at first launch** with no context, which gets more refusals; the product side of that timing is covered with push delivery design. - **Expecting a second prompt** after a refusal. There is none; the app can only point the person to Settings. - **Random identifiers** such as a fresh UUID for each reschedule, which leave the old reminder pending beside the new one. - **Thinking local reminders need a device token.** Local notifications never touch APNs; only remote ones need registration. - **Requesting `.timeSensitive`** to make a reminder urgent, instead of setting the content's interruption level with the entitlement.
- What changes if the app adds .provisional to the authorization options?With `.provisional` (iOS 12) the first call grants authorization without a prompt, and `authorizationStatus` reads `.provisional`. Notifications arrive quietly: no sound or banner and not on the lock screen, only in Notification Center's history, with Keep and Turn Off buttons, so the person decides after seeing one. The app still checks the status before scheduling, because the person can keep or turn them off at any time.
- Why is UNTimeIntervalNotificationTrigger(timeInterval: 30, repeats: true) invalid?When `repeats` is `true`, the documentation requires a time interval of 60 seconds or more; one-off triggers only need a value above zero. A repeating request also keeps firing until the app removes it with `removePendingNotificationRequests(withIdentifiers:)`, so a repeating reminder needs a stable identifier and a cancel path.
- What should the app do when requestAuthorization returns false?Accept the stored answer: later calls will not prompt again. Keep the feature working without alerts, read `notificationSettings()` when the person returns to the reminder screen, and, if they want reminders, send them to the app's notification settings in Settings rather than asking again.
- Calling requestAuthorization again shows the prompt again after a refusal.
- Each add with the same identifier creates a second pending reminder.
- Local reminders need APNs registration and a device token first.
- UNAuthorizationOptions.timeSensitive is how an app asks for urgent reminders.
- Permission granted once never needs checking before later scheduling.