Short answer

Two different things share the word "notification". NotificationCenter broadcasts messages inside your running app. UNUserNotificationCenter shows alerts to the user, even when the app is closed. For a local reminder: ask permission with requestAuthorization, add a UNNotificationRequest with a trigger, and set a delegate that implements willPresent so you decide how it looks while the app is open.

SWIFT TIPS · UIKIT · USER NOTIFICATIONS

First posted on June 11, 2018 for Swift 4, as "Get Notification and List Notification Swift 4". Rewritten on November 17, 2026. The NotificationCenter example was run on a Mac with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1. The local notification code was type-checked against the iOS 26.2 SDK in Swift 5 and Swift 6 modes with iOS 15 as the deployment target, but not run on a device.

In 2018 I built a small demo: tap a button, a row appears in a table, and a second later the phone shows a notification. The post introduced it as a demonstration of NSNotificationCenter, but the code actually used UNUserNotificationCenter, the framework for alerts the user sees. Those are two separate systems, and mixing up the names is common, so this rewrite covers both.

NotificationCenter: messages inside your app

NotificationCenter lets one part of your app announce that something happened, and any number of other parts react, without knowing about each other. The user never sees these. I ran this on a Mac:

import Foundation

extension Notification.Name {
    static let cartDidChange = Notification.Name("cartDidChange")
}

// 1. Observer with a block: keep the token, remove it when you're done
var received: [Int] = []
let token = NotificationCenter.default.addObserver(forName: .cartDidChange, object: nil, queue: nil) { note in
    received.append(note.userInfo?["count"] as? Int ?? -1)
}
NotificationCenter.default.post(name: .cartDidChange, object: nil, userInfo: ["count": 3])
NotificationCenter.default.post(name: .cartDidChange, object: nil, userInfo: ["count": 4])
NotificationCenter.default.removeObserver(token)
NotificationCenter.default.post(name: .cartDidChange, object: nil, userInfo: ["count": 5])
print("block observer received:", received, "(the post after removeObserver was not received)")

// 2. Posting is synchronous: the observer runs before post() returns
var order: [String] = []
let t2 = NotificationCenter.default.addObserver(forName: .cartDidChange, object: nil, queue: nil) { _ in order.append("observer") }
order.append("before post")
NotificationCenter.default.post(name: .cartDidChange, object: nil)
order.append("after post")
NotificationCenter.default.removeObserver(t2)
print("order:", order)

// 3. async sequence (macOS 12 / iOS 15)
let listener = Task {
    var counts: [Int] = []
    for await note in NotificationCenter.default.notifications(named: .cartDidChange) {
        counts.append(note.userInfo?["count"] as? Int ?? -1)
        if counts.count == 2 { break }
    }
    return counts
}
try await Task.sleep(nanoseconds: 100_000_000)
NotificationCenter.default.post(name: .cartDidChange, object: nil, userInfo: ["count": 7])
NotificationCenter.default.post(name: .cartDidChange, object: nil, userInfo: ["count": 8])
print("async sequence received:", await listener.value)
block observer received: [3, 4] (the post after removeObserver was not received)
order: ["before post", "observer", "after post"]
async sequence received: [7, 8]

Three things the output shows:

  • Remove block observers. addObserver(forName:object:queue:using:) returns a token. After removeObserver(token), the third post wasn't received. If you never remove it, the block keeps running for as long as the token lives.
  • Posting is synchronous. The observer ran between "before post" and "after post". A slow observer slows down whoever posts, so keep observers short.
  • An async sequence works too. Since iOS 15, notifications(named:) gives an AsyncSequence you can loop over in a Task, which received both values.

Local notifications: alerts the user sees

import UIKit
import UserNotifications

final class ReminderViewController: UIViewController, UNUserNotificationCenterDelegate {
    private let center = UNUserNotificationCenter.current()

    override func viewDidLoad() {
        super.viewDidLoad()
        center.delegate = self   // set early, before any notification can arrive
    }

    @IBAction func remindMeTapped(_ sender: UIButton) {
        Task {
            guard await askPermissionIfNeeded() else { return }   // explain in your UI if denied
            let content = UNMutableNotificationContent()
            content.title = "Time to stretch"
            content.body = "You asked for a reminder."
            content.sound = .default
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
            let request = UNNotificationRequest(identifier: "stretch-reminder", content: content, trigger: trigger)
            try? await center.add(request)
        }
    }

    private func askPermissionIfNeeded() async -> Bool {
        let settings = await center.notificationSettings()
        switch settings.authorizationStatus {
        case .authorized, .provisional, .ephemeral:
            return true
        case .notDetermined:
            return (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false
        default:
            return false
        }
    }

    // While the app is open: decide how the notification is shown
    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
                                            willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
        [.banner, .list, .sound]
    }
}

What each part does:

  • Permission first. askPermissionIfNeeded() reads the current settings and only asks when the status is not determined. Apple's documentation says the system only prompts the first time and later requests don't prompt again, so after a no the code returns false and your screen should explain how to turn notifications on in Settings.
  • The request. Content, a trigger, and an identifier. Apple's documentation says that scheduling a request with an identifier that's already scheduled replaces the old one, which is handy for "remind me later" buttons tapped twice.
  • Set the delegate early. The code sets center.delegate in viewDidLoad. In a real app, do it in the app delegate at launch, so notifications that arrive before this screen opens are handled too.

Notifications while the app is open

The 2018 demo fired its notification one second after the tap, while the app was still on screen. What happens then depends on the delegate. Apple's documentation for userNotificationCenter(_:willPresent:) says that if you set a delegate but don't implement this method, the system behaves as if you passed no presentation options, so nothing is shown. If you don't set a delegate at all, the system uses the notification's original options.

Relying on that difference is fragile. Implement willPresent and return what you want, as the code does with banner, list and sound. The method is marked nonisolated and only returns a value instead of touching the UI, which is how it type-checked cleanly in both Swift 5 and Swift 6 mode.

A quick check for your project

  1. Search for requestAuthorization. If it runs at launch with no context, move it to the moment the user asks for something that needs notifications.
  2. Check that UNUserNotificationCenter.current().delegate is set in the app delegate, and that willPresent is implemented.
  3. Search for addObserver(forName: and check that each returned token is stored and removed.

What the 2018 version said

The original asked for permission in viewDidLoad, appended a line of text to a table on each button tap, and scheduled a one-second UNTimeIntervalNotificationTrigger with a title, subtitle and body. It used a single identifier, "cNotif", so a second tap replaced the first pending notification, and it didn't set a notification center delegate.

Sources