Skip to content
Commitwise
Menu
iOS Development

Universal links, widgets and App Intents

Open the right screen from a web link with universal links and an apple-app-site-association file, treat incoming URLs as untrusted input, share data with a widget through an App Group, build timelines and interactive widgets, and expose actions to Siri, Shortcuts and Spotlight with App Intents.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

Marketing sends a newsletter with a link to this week’s recipe. On iPhones with the app installed it should open the recipe in the app; without the app, the website. Product also wants a home screen widget showing tonight’s dinner with a “Cooked” button, and “What’s for dinner?” to work in Siri. The first build opens Safari instead of the app, the widget is always empty, and a security review flags that any web page can make the app add items to the user’s cart.

Apps don’t live only inside their own icon anymore. Users arrive from links, glance at widgets, and ask Siri. Each entry point runs in a different context, sometimes in a different process, and each one has its own rules. This lesson covers the three you’ll meet in almost every senior iOS role.

New to some of these? Open what you need, or skip ahead.

Basics:What is a deep link?

A deep link is a link that opens a specific screen inside an app, not just its home screen: a recipe, an order, a chat. The app reads the URL and navigates to the right place. In SwiftUI, URLs arrive through the .onOpenURL modifier. See deep linkDeep linkA URL that opens a specific screen inside an app, from an email, a notification, a QR code or another app.Open in glossary →.

Basics:What is an app extension?

An app extension is a small separate program that ships inside your app and runs outside it: a widget, a share sheet, a notification service. It runs in its own process, with its own memory limits, and it can’t read the app’s private files or UserDefaults. To share data, the app and the extension join the same App Group, which gives them a shared folder.

Part Not started

Widgets and App Intents

A widget isn’t a tiny copy of your app that keeps running. It’s closer to a slideshow: your widget extension gives iOS a list of entries (what to show, and from when), iOS renders them and swaps them at the right times. Your code runs only when iOS asks for a new list.

Three things follow from that:

App IntentsApp IntentA Swift type describing one of your app's actions so the system can run it from widgets, Siri, Shortcuts or Spotlight.Open in glossary → describe your app’s actions in a way the whole system understands. The same intent can be a widget button, a Siri command, a Shortcuts action and a Spotlight suggestion.

Widgets are SwiftUI views archived by an extension and rendered by the system. A TimelineProvider (or AppIntentTimelineProvider for configurable widgets) returns entries and a reload policy (.atEnd, .after(date), .never); reloads beyond the system’s daily budget (roughly dozens per widget, more for frequently viewed widgets) are deferred, and calls to WidgetCenter.reloadTimelines(ofKind:) from the foreground app don’t count against it. The extension has a tight memory limit (about 30 MB), little time, and unreliable network, so the app should write a ready-to-render snapshot to the App Group container. Interactive widgets (iOS 17) attach AppIntents to Button and Toggle; the intent runs in the extension process by default and the system reloads the timeline afterwards. App Intents are the shared action layer: AppEntity and EntityQuery model your data for parameters, AppShortcutsProvider registers phrases that work with zero setup, and the same intents back Spotlight, Siri, the Action button, Control Center controls (iOS 18) and Apple Intelligence integrations. Keep intents thin: they call the same domain services the app uses.

import WidgetKit
import SwiftUI
import AppIntents

// Shared by the app and the widget extension (both in the App Group "group.com.example.recipes")
enum SharedStore {
    static let defaults = UserDefaults(suiteName: "group.com.example.recipes")!

    static func tonight() -> RecipeSnapshot? {
        defaults.data(forKey: "tonight").flatMap { try? JSONDecoder().decode(RecipeSnapshot.self, from: $0) }
    }
    static func save(tonight recipe: RecipeSnapshot) {        // called by the app
        defaults.set(try? JSONEncoder().encode(recipe), forKey: "tonight")
        WidgetCenter.shared.reloadTimelines(ofKind: "Dinner")
    }
    static func markCooked(_ id: Int) { defaults.set(id, forKey: "cookedID") }
}

struct DinnerEntry: TimelineEntry {
    let date: Date
    let recipe: RecipeSnapshot?
    let isCooked: Bool
}

struct DinnerProvider: TimelineProvider {
    func placeholder(in context: Context) -> DinnerEntry {
        DinnerEntry(date: .now, recipe: .sample, isCooked: false)
    }
    func getSnapshot(in context: Context, completion: @escaping (DinnerEntry) -> Void) {
        completion(currentEntry())
    }
    func getTimeline(in context: Context, completion: @escaping (Timeline<DinnerEntry>) -> Void) {
        let nextMorning = Calendar.current.nextDate(after: .now, matching: DateComponents(hour: 6),
                                                    matchingPolicy: .nextTime)!
        completion(Timeline(entries: [currentEntry()], policy: .after(nextMorning)))   // one reload a day
    }
    private func currentEntry() -> DinnerEntry {
        let recipe = SharedStore.tonight()
        return DinnerEntry(date: .now, recipe: recipe,
                           isCooked: recipe != nil && SharedStore.defaults.integer(forKey: "cookedID") == recipe?.id)
    }
}

struct DinnerWidget: Widget {
    var body: some WidgetConfiguration {
        StaticConfiguration(kind: "Dinner", provider: DinnerProvider()) { entry in
            DinnerWidgetView(entry: entry)
                .containerBackground(.fill.tertiary, for: .widget)
        }
        .configurationDisplayName("Tonight’s dinner")
        .supportedFamilies([.systemSmall, .systemMedium])
    }
}

struct DinnerWidgetView: View {
    let entry: DinnerEntry

    var body: some View {
        if let recipe = entry.recipe {
            VStack(alignment: .leading) {
                Text(recipe.title).font(.headline)
                Button(intent: MarkCookedIntent(recipeID: recipe.id)) {        // runs without opening the app
                    Label(entry.isCooked ? "Cooked" : "Mark cooked",
                          systemImage: entry.isCooked ? "checkmark.circle.fill" : "circle")
                }
            }
            .widgetURL(URL(string: "https://recipes.example.com/r/\(recipe.id)"))   // tapping elsewhere opens it
        } else {
            Text("Plan tonight’s dinner")
        }
    }
}

struct MarkCookedIntent: AppIntent {
    static let title: LocalizedStringResource = "Mark Recipe as Cooked"
    @Parameter(title: "Recipe ID") var recipeID: Int

    init() {}
    init(recipeID: Int) { self.recipeID = recipeID }

    func perform() async throws -> some IntentResult {
        SharedStore.markCooked(recipeID)          // the widget's timeline reloads after this returns
        return .result()
    }
}

struct TonightsDinnerIntent: AppIntent {
    static let title: LocalizedStringResource = "Tonight’s Dinner"

    func perform() async throws -> some IntentResult & ProvidesDialog {
        let title = SharedStore.tonight()?.title ?? "nothing planned yet"
        return .result(dialog: "Tonight it’s \(title).")
    }
}

struct RecipeShortcuts: AppShortcutsProvider {
    static var appShortcuts: [AppShortcut] {
        AppShortcut(intent: TonightsDinnerIntent(),
                    phrases: ["What’s for dinner in \(.applicationName)"],
                    shortTitle: "Tonight’s Dinner",
                    systemImageName: "fork.knife")
    }
}
  • SharedStore uses UserDefaults(suiteName:) with the App Group id, so the app and the widget read and write the same data. Both targets need the App Group capability.
  • getTimeline returns one entry and says “ask me again tomorrow at 6”. When the user plans a new dinner, the app saves it and calls reloadTimelines.
  • Button(intent:) runs MarkCookedIntent right on the home screen. iOS reloads the widget afterwards, so the checkmark appears.
  • widgetURL opens the recipe through the same universal link the newsletter uses.
  • RecipeShortcuts makes “What’s for dinner in Recipes” work with Siri as soon as the app is installed, no setup needed.
Spot the bugThe widget is always empty

Tap the line with the bug.

// In the app, after the user picks tonight's recipe
UserDefaults.standard.set(try? JSONEncoder().encode(recipe), forKey: "tonight")
WidgetCenter.shared.reloadTimelines(ofKind: "Dinner")

// In the widget's timeline provider
let data = UserDefaults.standard.data(forKey: "tonight")
let recipe = data.flatMap { try? JSONDecoder().decode(RecipeSnapshot.self, from: $0) }

Production puzzles

Predict the output

A stock-watch widget returns a timeline with .after(now + 60 seconds) on every reload, and the widget fetches prices from the network in getTimeline. Users report it updates every 15 to 60 minutes at best, and sometimes shows a placeholder. Why?

Exercisehard

Design the entry points

A habit tracker wants: a widget with today’s habits and check-off buttons, “Log water” in Siri and on the Action button, Spotlight results for each habit, and links from reminder emails. Sketch the architecture so logic isn’t duplicated across the app, the widget extension and intents.

›

Find the one module every entry point can share, and decide where the data lives so both processes can reach it safely.

SolutionTry it yourself first
  • A shared domain module (HabitsCore, a Swift package) with models, a HabitStore and the “log habit” use case. The app, the widget extension and intents all call it; none contains business logic of its own.
  • Storage in the App Group container (SwiftData or SQLite with a shared store URL, or a JSON snapshot for the widget), with care for concurrent writes from two processes: a single writer API, file coordination or SQLite WAL mode.
  • App Intents: LogHabitIntent with an AppEntity HabitEntity and an EntityQuery, used by widget buttons, Siri, Shortcuts and the Action button; AppShortcutsProvider phrases; IndexedEntity (iOS 18) or Core Spotlight donations for Spotlight.
  • Widget: reads the snapshot, Button(intent: LogHabitIntent(habit:)); the app calls reloadTimelines after changes; timelines roll over at midnight.
  • Links: /h/<id> universal links parsed into Route.habit(id:), opening the habit; logging stays an explicit tap.
  • Testing: intents are plain types with perform(), unit-tested against an in-memory store.
Exercisemedium

A widget that changes at midnight

A “Recipe of the day” widget shows a different recipe each day. The app downloads the next 7 days’ recipes once a week and saves them to the App Group. Write getTimeline so the widget changes at midnight without waking your code every day.

›

A timeline can contain several entries, each with its own date.

SolutionTry it yourself first
func getTimeline(in context: Context, completion: @escaping (Timeline<RecipeEntry>) -> Void) {
    let calendar = Calendar.current
    let week = SharedStore.upcomingRecipes()            // [(day: Date, recipe: RecipeSnapshot)]
    let entries = week.map { item in
        RecipeEntry(date: calendar.startOfDay(for: item.day), recipe: item.recipe)
    }
    // After the last entry, ask again (by then the app should have downloaded more)
    completion(Timeline(entries: entries, policy: .atEnd))
}

iOS shows each entry from its date onwards, so the widget switches at midnight by itself. Your code runs again only when the entries run out or the app calls reloadTimelines.

  • Widgets: separate process, archived SwiftUI, ~30 MB, short runtime. Data via App Group snapshots; app calls WidgetCenter.reloadTimelines (not budgeted from the foreground).
  • Timeline policies are hints within a daily reload budget: precompute future entries; no minute-level polling; Live Activities for live data.
  • Interactive widgets: Button/Toggle(intent:); intents run in the extension, the timeline reloads afterwards.
  • App Intents: one action layer for widgets, Siri, Shortcuts, Spotlight, Action button, controls. AppEntity + EntityQuery; AppShortcutsProvider for zero-setup phrases.
  • Shared domain module for app, extensions and intents; mind concurrent access to shared storage.

Check this part

  1. How does a widget get data the app saved?

  2. What runs when the user taps Button(intent:) in a widget?

  3. A widget asks to reload every minute. What actually happens?

  4. What makes an App Intent available to Siri with no setup by the user?

A widget is an extension in its own process: it renders entries from a timeline provider and can't read the app's private data, so the app writes a snapshot to an App Group and calls WidgetCenter to reload. Reloads are budgeted, so plan timelines. Interactive widgets run AppIntents from Button(intent:). App Intents also power Siri, Shortcuts, Spotlight and controls; AppShortcutsProvider makes them available without setup.

Key takeaways

  • Universal links are https links that open the app, or the website if it isn’t installed.
  • They need the Associated Domains capability and an apple-app-site-association file.
  • Treat incoming URLs as untrusted: parse, validate, and only navigate.
  • Widgets show timeline entries and read data from an App Group.
  • App Intents turn app actions into widget buttons, Siri commands and Shortcuts.
  • Know the AASA, CDN and user opt-out behavior; plan link changes ahead of campaigns.
  • Route every entry point through one typed router; stash routes behind authentication.
  • Design widgets around budgets and process limits; the app prepares snapshots.
  • Put logic in a shared module; intents, widgets and the app are thin adapters over it.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.