Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 46 ยท Polish and Platform Features

Notifications, Widgets and App Intents

Understand iOS local and push notifications, WidgetKit timelines, App Intents for Siri and Shortcuts, and Live Activities, with runnable stand-ins for triggers and timelines.

Your app does not only live inside its own window. It can nudge people with a notification, show a glance at its data on the Home Screen, answer a Siri request, or keep a delivery tracker alive on the Lock Screen. These features share one design idea: the system runs a small piece of your code at the right moment and shows the result, even when your app is not open. That is powerful, and it explains why they behave differently from normal SwiftUI screens.

This lesson gives you the map: local and push notifications, WidgetKit timelines, App Intents and Live Activities. The real framework code is read-only because it needs a device, entitlements and extension targets. The two TryIts are stand-ins that run the core logic: how a calendar trigger finds its next fire time, and how a widget timeline is built from future entries. You should know the app lifecycle and UserDefaults and files before reading on.

Four ways to reach users outside your app

Notifications A message at a chosen time.
Widgets Glanceable views of your data.
App Intents Actions for Siri and Shortcuts.
Live Activities A running event on the Lock Screen.

The system runs your code, not you.

1 / 2

Local notifications

A local notification is scheduled by the app itself, with no server. Typical uses are reminders, timers and habit nudges. The UserNotifications framework has three steps: ask permission, describe the content, and choose a trigger.

Swift
import UserNotifications

func scheduleReminder() async throws {
    let center = UNUserNotificationCenter.current()

    let granted = try await center.requestAuthorization(options: [.alert, .sound, .badge])
    guard granted else { return }

    let content = UNMutableNotificationContent()
    content.title = "Time to stretch"
    content.body = "Two minutes is enough."
    content.sound = .default

    var time = DateComponents()
    time.hour = 9
    time.minute = 30
    let trigger = UNCalendarNotificationTrigger(dateMatching: time, repeats: true)

    let request = UNNotificationRequest(
        identifier: "daily-stretch",
        content: content,
        trigger: trigger
    )
    try await center.add(request)
}

Some practical rules:

  • Ask at a good moment. The system shows the permission prompt only once. Explain the value first, then ask when the user takes an action that makes it obvious. If they decline, the app can only point them to Settings.
  • Identifiers matter. Adding a request with an existing identifier replaces the old one, which is how you reschedule. Remove with removePendingNotificationRequests(withIdentifiers:).
  • Triggers come in three kinds: UNTimeIntervalNotificationTrigger (after N seconds; repeating ones need at least 60 seconds), UNCalendarNotificationTrigger (matching date components, like "every day at 9:30"), and UNLocationNotificationTrigger (entering or leaving a region).
  • Foreground behavior. By default a notification is silent while your app is open. Implement userNotificationCenter(_:willPresent:) in a UNUserNotificationCenterDelegate and return options such as .banner and .sound to show it anyway. Handle taps in userNotificationCenter(_:didReceive:), where you can route to a screen with the deep link techniques you will meet later.
  • Limits. The system keeps only a limited number of pending local notifications per app (64 is the long-standing number), so schedule the next few rather than a whole year.

The first TryIt runs the same logic the calendar trigger uses. Given the current moment and a set of date components, the system finds the next matching date. We use Calendar.nextDate(after:matching:matchingPolicy:) with a fixed time zone so the output is always the same.

Swift When does a calendar trigger fire next?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

If you ask at 08:00 the daily reminder fires the same morning; ask at 10:15 and it waits until tomorrow. This is what repeats: true on a calendar trigger does for you without any rescheduling.

Push notifications

A push notification comes from a server through Apple Push Notification service (APNs). The flow has four parties:

sequenceDiagram
    participant App
    participant APNs as Apple (APNs)
    participant Server as Your server
    participant Phone as Device
    App->>APNs: register for remote notifications
    APNs-->>App: device token
    App->>Server: send token
    Server->>APNs: push with payload and token
    APNs->>Phone: deliver notification

The app registers, your server stores the token, and every push travels through APNs.

In an app, you enable the Push Notifications capability, call UIApplication.shared.registerForRemoteNotifications() after permission is granted, and receive the token in an app delegate method (SwiftUI apps attach one with @UIApplicationDelegateAdaptor, as covered in the app lifecycle lesson). Send the token to your backend. Tokens can change, so send it on every launch and let the server update its record.

The server sends an HTTP/2 request to APNs, authenticating with a signing key from your developer account. The payload is JSON with an aps dictionary:

JSON
{
  "aps": {
    "alert": { "title": "Order shipped", "body": "Arrives Thursday." },
    "badge": 1,
    "sound": "default"
  },
  "orderId": "A-1042"
}

Anything outside aps is your own data, which you can read in didReceive and use to navigate. Keep payloads small, never put secrets in them, and treat delivery as best effort. A silent push (content-available) can wake the app briefly to fetch data, but the system throttles it and may skip it, so never depend on it for correctness. Notification Service Extensions can modify a push before display, for example to attach an image or decrypt content.

Widgets with WidgetKit

A widget is a SwiftUI view in an extension target. It is not a mini running app: the system asks your extension for a timeline, a list of entries with dates, renders each entry as a static snapshot, and swaps them at the right moments.

Swift
import WidgetKit
import SwiftUI

struct StreakEntry: TimelineEntry {
    let date: Date
    let streak: Int
}

struct StreakProvider: TimelineProvider {
    func placeholder(in context: Context) -> StreakEntry {
        StreakEntry(date: .now, streak: 7)
    }

    func getSnapshot(in context: Context, completion: @escaping (StreakEntry) -> Void) {
        completion(StreakEntry(date: .now, streak: 7))
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<StreakEntry>) -> Void) {
        let now = Date()
        let entry = StreakEntry(date: now, streak: Store.currentStreak())
        let tomorrow = Calendar.current.startOfDay(for: now).addingTimeInterval(86_400)
        completion(Timeline(entries: [entry], policy: .after(tomorrow)))
    }
}

struct StreakWidget: Widget {
    var body: some WidgetConfiguration {
        StaticConfiguration(kind: "StreakWidget", provider: StreakProvider()) { entry in
            Text("๐Ÿ”ฅ \(entry.streak) days")
        }
        .configurationDisplayName("Streak")
        .supportedFamilies([.systemSmall, .accessoryCircular])
    }
}

Key ideas:

  • placeholder shows redacted content while loading, getSnapshot serves the widget gallery, and getTimeline provides the real entries.
  • The timeline policy says when to ask again: .atEnd (after the last entry), .after(date), or .never (only when your app calls WidgetCenter.shared.reloadTimelines(ofKind:)).
  • The system decides how often a widget actually refreshes, based on a budget that depends on user behavior. Do not expect second-by-second updates. For counting time, use the date-aware views such as Text(date, style: .timer) which the system updates for free.
  • Families include .systemSmall, .systemMedium, .systemLarge and Lock Screen accessories such as .accessoryCircular. Read @Environment(\.widgetFamily) to adapt.
  • The extension is a separate process. To share data with your app, use an App Group container (shared UserDefaults(suiteName:) or files), not the app's private storage.
  • Widgets are not scrollable and interact only through links (widgetURL, Link) or, since iOS 17, Button and Toggle that run an App Intent.

The second TryIt models the timeline step. It builds a list of dated entries for a countdown widget and picks the entry the system would show at a given moment.

Swift A widget timeline and which entry is shown

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

At hour 8 no entry has started, so the widget would still show the previous timeline or its placeholder. The key point is that the rendering for all three days was decided in advance, with no app code running later.

App Intents

An App Intent is a typed action your app exposes to the system. Siri, the Shortcuts app, Spotlight, widget buttons and Control Center controls can all run the same intent.

Swift
import AppIntents

struct LogWaterIntent: AppIntent {
    static let title: LocalizedStringResource = "Log a glass of water"

    @Parameter(title: "Glasses", default: 1)
    var glasses: Int

    func perform() async throws -> some IntentResult & ProvidesDialog {
        let total = Store.addWater(glasses)
        return .result(dialog: "That makes \(total) today.")
    }
}

struct WaterShortcuts: AppShortcutsProvider {
    static var appShortcuts: [AppShortcut] {
        AppShortcut(
            intent: LogWaterIntent(),
            phrases: ["Log water in \(.applicationName)"],
            shortTitle: "Log water",
            systemImageName: "drop"
        )
    }
}

@Parameter values can be filled by Siri's conversation or the Shortcuts editor. AppEntity types let you expose your own objects (a note, a habit) so users can pick them. perform() runs without your UI, so it must be fast, work through shared storage and not assume a view is on screen. A widget Button(intent: LogWaterIntent()) runs the same code and then reloads the timeline. Write the logic in a plain type, such as a service you can test, and keep the intent a thin wrapper.

Live Activities

A Live Activity shows the state of something happening right now, such as a delivery, a game score or a timer, on the Lock Screen and the Dynamic Island. It uses ActivityKit:

Swift
import ActivityKit

struct DeliveryAttributes: ActivityAttributes {
    struct ContentState: Codable, Hashable {
        var status: String
        var minutesLeft: Int
    }
    var orderNumber: String      // fixed for the whole activity
}

let attributes = DeliveryAttributes(orderNumber: "A-1042")
let state = DeliveryAttributes.ContentState(status: "Preparing", minutesLeft: 25)
let activity = try Activity.request(
    attributes: attributes,
    content: .init(state: state, staleDate: nil),
    pushType: .token
)

// later
await activity.update(.init(state: .init(status: "On the way", minutesLeft: 8), staleDate: nil))
await activity.end(nil, dismissalPolicy: .immediate)

The attributes never change; ContentState does. The interface is a widget-extension view built with ActivityConfiguration, with compact, expanded and minimal Dynamic Island layouts. The app can update it locally while running, but for most real cases the server updates it with a push using pushType: .token. Activities are time-limited (the system ends them after about eight hours) and payloads are small, so they suit short-lived events, not permanent dashboards.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you add a notification request whose identifier already exists?

    Identifiers act as keys. Re-adding a request with the same identifier replaces the pending one, which is how you reschedule.
  2. 2. Why should a widget not expect to update every second?

    A widget is rendered from timeline entries on the system's schedule. For ticking times use date-aware views like Text(date, style: .timer).
  3. 3. How can a widget extension and the main app share data?

    They are separate processes with separate sandboxes. An App Group provides a shared container for UserDefaults suites and files.
  4. 4. What is the purpose of the device token in push notifications?

    The token is an address that APNs understands. Your app sends it to your server, which includes it when sending pushes.
  5. 5. In ActivityKit, which part of a Live Activity can change while it runs?

    Attributes stay fixed for the lifetime of the activity; ContentState is the part you update.

Summary

  • Local notifications use UNUserNotificationCenter: request permission, build content, pick a trigger (interval, calendar or location) and add a request with an identifier.
  • Push notifications travel through APNs using a device token your server stores; payloads are small JSON with an aps dictionary, and delivery is best effort.
  • Widgets are timelines of dated entries rendered by the system, refreshed by a policy and a budget, and share data with the app through an App Group.
  • App Intents expose typed actions to Siri, Shortcuts, Spotlight and interactive widgets; keep logic in testable plain types.
  • Live Activities use fixed attributes plus a changing ContentState, shown on the Lock Screen and Dynamic Island, and are short-lived.

Next: UIKit Interoperability.