Pocket How
System features

WidgetKit interactive widgets: timelines, reload budgets and App Intents

iOS 17+, iPadOS 17+. Intermediate. By Cihat Salik, .

Short answer

Give WidgetKit a timeline with the entries you can predict, reload it from the app when data changes, and keep shared data in an App Group. For taps, use Button(intent:) or Toggle(isOn:intent:) on iOS 17+; WidgetKit runs the intent and always reloads the timeline afterwards. Support the accented rendering mode, because tinted and clear Home Screens use it.

The problem

A widget looks like a small SwiftUI view, but it does not behave like one. WidgetKit renders it in a separate process from an archived snapshot, so @State, bindings and onTapGesture never run. Your extension wakes up only when the system asks for a timeline, and the system rations those requests. Widgets go stale when developers treat them as live views, and they burn their reload budget when developers poll a server. The fix is to plan the timeline, push changes from the app, and route every tap through an App Intent.

How WidgetKit decides when to redraw

Apple’s Keeping a widget up to date describes three update paths: a timeline for predictable changes, a reload request from your app when data changes, and WidgetKit push notifications from your server.

The timeline is the main one. Your TimelineProvider returns an array of entries, each with a date, plus a reload policy:

  • .atEnd asks for a new timeline after the last entry’s date. It is the default.
  • .after(_:) asks for a new timeline at a date you pick, earlier or later than the last entry.
  • .never waits until your app calls WidgetCenter.

WidgetKit gives each widget instance its own budget over a rolling 24-hour window. For a widget the person views often, Apple says the budget is typically 40 to 70 refreshes, roughly one every 15 to 60 minutes. Entries should be at least about 5 minutes apart. Some reloads do not count against the budget: when your app is in the foreground, when it has an active audio or navigation session, when the widget performs an app intent, and when locale, Dynamic Type or accessibility settings change.

Two practical consequences follow. First, generate as many future entries as you can predict instead of reloading often. Second, if you show a countdown or elapsed time, use a self-updating date text (Text(date, style: .timer) or .relative) so WidgetKit animates it without any reload at all.

One warning from the same page is easy to miss. If many devices use .after(_:) with the same wall-clock date and fetch from your server on reload, they all hit your server at once. Add jitter, or have the app fetch and write to shared storage instead.

Share data with an App Group

The widget extension is a separate process with its own container. To read what the app wrote, both targets need the same App Group capability, and both read and write through the group container. The Create with Swift tutorial Creating an interactive widget with SwiftUI by Tiago Gomes Pereira and Matteo Altobello builds a water tracker this way: a UserDefaults suite in the group, a shared counter type in both targets, and a WidgetCenter reload after every change. That shape scales well, so the example below uses it. For anything larger than a few values, put a SwiftData or SQLite store in the group container.

import Foundation
import WidgetKit

enum CupStore {
    static let groupID = "group.com.example.cups"
    static let widgetKind = "CupWidget"

    static var defaults: UserDefaults {
        UserDefaults(suiteName: groupID)!
    }

    static var count: Int {
        defaults.integer(forKey: "cups")
    }

    static func add() {
        defaults.set(count + 1, forKey: "cups")
    }

    static func reset() {
        defaults.set(0, forKey: "cups")
        WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)
    }
}

The force unwrap is deliberate: a missing App Group is a configuration bug you want to see on the first run, not a silent fallback to standard defaults that the widget can never read.

Call reloadTimelines(ofKind:) from the app whenever the data behind a widget changes. If the person has configured several instances, Apple suggests checking WidgetCenter.shared.getCurrentConfigurations first so you only reload a kind that is actually on screen.

Add a button that runs an App Intent

Since iOS 17, widgets can contain Button and Toggle views that take an AppIntent. Apple’s Adding interactivity to widgets and Live Activities lists the families that support them: systemSmall, systemMedium, systemLarge, systemExtraLarge, systemExtraLargePortrait, and on iPhone and iPad, accessoryCircular and accessoryRectangular. On a locked device the controls stay inactive until the person authenticates.

The intent runs in the widget extension’s process by default. When perform() returns, WidgetKit reloads the timeline, and Apple states that a button or toggle interaction always guarantees that reload. So the rule is simple: finish writing your data before you return.

import AppIntents

struct AddCupIntent: AppIntent {
    static let title: LocalizedStringResource = "Add a cup of water"
    static let description = IntentDescription("Logs one cup of water for today.")

    func perform() async throws -> some IntentResult {
        CupStore.add()
        return .result()
    }
}

Add this file to both the app target and the widget extension target. Apple recommends that so you can reuse the same button in the app, and it means the intent also appears in Shortcuts for free.

Now the provider, entry and view:

import SwiftUI
import WidgetKit

struct CupEntry: TimelineEntry {
    let date: Date
    let cups: Int
}

struct CupProvider: TimelineProvider {
    func placeholder(in context: Context) -> CupEntry {
        CupEntry(date: .now, cups: 4)
    }

    func getSnapshot(in context: Context, completion: @escaping (CupEntry) -> Void) {
        completion(CupEntry(date: .now, cups: CupStore.count))
    }

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

struct CupWidgetView: View {
    let entry: CupEntry

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            Text(entry.cups, format: .number)
                .font(.system(.largeTitle, design: .rounded, weight: .bold))
                .contentTransition(.numericText())
                .invalidatableContent()
                .widgetAccentable()
            Text("cups today")
                .font(.caption)
                .foregroundStyle(.secondary)
            Spacer(minLength: 0)
            Button(intent: AddCupIntent()) {
                Label("Add cup", systemImage: "plus")
            }
            .buttonStyle(.borderedProminent)
        }
        .frame(maxWidth: .infinity, alignment: .leading)
        .containerBackground(.blue.gradient, for: .widget)
    }
}

struct CupWidget: Widget {
    var body: some WidgetConfiguration {
        StaticConfiguration(kind: CupStore.widgetKind, provider: CupProvider()) { entry in
            CupWidgetView(entry: entry)
        }
        .configurationDisplayName("Water")
        .description("Log a cup without opening the app.")
        .supportedFamilies([.systemSmall, .systemMedium])
    }
}

The policy here is .after(tomorrow) because the count only changes when someone taps, and taps reload the timeline anyway. The midnight reload resets the display for the new day. The tutorial uses .never for the same reason; the dated policy is safer once a daily reset matters.

invalidatableContent() (iOS 17) tells the system which views are waiting for new data, so it can show a pending state. That matters most for iPhone widgets shown on a Mac, where Apple notes the tap travels to the iPhone, the intent runs there, and the new timeline travels back. Use it on the values that change, not on every view.

Toggles and parameters

A widget Toggle takes a plain Bool, not a binding, and flips its appearance optimistically before perform() finishes. If the action can fail, for example a server sync, write the confirmed state to shared storage and let the reload correct the toggle. Apple’s guidance is to show an error in the widget rather than leave a toggle that lies.

Widgets never resolve parameters for you, unlike Siri. Pass values in an initializer:

import AppIntents

struct CompleteTaskIntent: AppIntent {
    static let title: LocalizedStringResource = "Complete task"

    @Parameter(title: "Task ID")
    var taskID: String

    init() {}

    init(taskID: String) {
        self.taskID = taskID
    }

    func perform() async throws -> some IntentResult {
        try await TaskStore.shared.complete(id: taskID)
        return .result()
    }
}

TaskStore stands for your own shared persistence; it is left out here. In the view, Toggle(isOn: task.isDone, intent: CompleteTaskIntent(taskID: task.id)) { Text(task.title) } wires it up.

If an intent must run in the app’s process, conform it to LiveActivityIntent, AudioPlaybackIntent or ForegroundContinuableIntent, or set openAppWhenRun. Then it only needs to be in the app target.

Support tinted and clear Home Screens

On iOS 18 people can tint the Home Screen, and on iOS 26 they can also pick a clear Liquid Glass look. In both cases WidgetKit renders your widget in the accented rendering mode. Apple’s accented rendering guide explains what the system does: it tints primary and accented content white on iOS and macOS, tints opaque images a single white, and replaces your background with a themed glass or tinted effect.

So a full-bleed photo becomes a white rectangle unless you handle it. The tools:

  • @Environment(\.widgetRenderingMode) tells you whether you are in fullColor, accented or vibrant.
  • widgetAccentable() (iOS 16) puts a view in the accent group. Unmarked views form the primary group.
  • widgetAccentedRenderingMode(_:) (iOS 18) controls an Image in accented mode: .accented, .desaturated, .accentedDesaturated or .fullColor.
import SwiftUI
import WidgetKit

struct CoverImage: View {
    let name: String

    var body: some View {
        if #available(iOS 18.0, *) {
            Image(name)
                .resizable()
                .scaledToFill()
                .widgetAccentedRenderingMode(.fullColor)
        } else {
            Image(name)
                .resizable()
                .scaledToFill()
        }
    }
}

Apple reserves .fullColor for media such as album art and book covers, and recommends .desaturated or .accentedDesaturated for most other images. Matteo Altobello’s Create with Swift article on tint mode adds a useful trick: when an image still renders as a white block, .luminanceToAlpha() turns brightness into transparency so the shape survives tinting.

Older posts can mislead here. Majid Jabrayilov’s Lock screen widgets in SwiftUI correctly described accented mode as watchOS-only in 2022, and it is still a good read on the vibrant mode the Lock Screen and StandBy use. Since iOS 18 that statement no longer holds, so test the accented mode on iPhone too.

Widgets on more surfaces

The same widget code now reaches more places, and each has quirks:

  • StandBy and CarPlay use your systemSmall widget. Apple’s StandBy and CarPlay article says CarPlay shows it in full color with the background removed, so make the background removable and use large, glanceable type. Buttons work only on touchscreen cars. The WWDC25 session What’s new in widgets says CarPlay widgets arrived in iOS 26 for all CarPlay cars.
  • visionOS 26 shows iPhone and iPad widgets automatically and adds supportedMountingStyles(_:), widgetTexture(_:) and the levelOfDetail environment value, per the same session.
  • The Mac shows iPhone widgets on the desktop and in Notification Center, which is why invalidatableContent() matters.
  • systemExtraLargePortrait, introduced in visionOS 26, is available on iOS, iPadOS and macOS 27 according to the WWDC26 session WidgetKit foundations. Gate it:
import WidgetKit

extension CupWidget {
    static var families: [WidgetFamily] {
        if #available(iOS 27.0, *) {
            [.systemSmall, .systemMedium, .systemExtraLargePortrait]
        } else {
            [.systemSmall, .systemMedium]
        }
    }
}

Then pass .supportedFamilies(Self.families).

Push updates from your server

When the data changes on a server and the app is not running, iOS 26 lets a widget receive WidgetKit push notifications. Apple’s push update guide lays out the pieces: a type conforming to WidgetPushHandler that sends the token from pushTokenDidChange(_:widgets:) to your server, .pushHandler(_:) on the configuration, the Push Notifications capability on the widget extension, and an APNs request with apns-push-type: widgets, topic <bundle ID>.push-type.widgets and "content-changed": true in aps.

import WidgetKit

struct CupPushHandler: WidgetPushHandler {
    func pushTokenDidChange(_ pushInfo: WidgetPushInfo, widgets: [WidgetInfo]) {
        let token = pushInfo.token.map { String(format: "%02x", $0) }.joined()
        Task { try await TokenUploader.send(widgetToken: token, kinds: widgets.map(\.kind)) }
    }
}

TokenUploader is your networking code. These pushes are budgeted and delivered opportunistically like timeline reloads, so they add to a timeline and never replace it. You cannot use broadcast channels for widgets. During development, WidgetKit developer mode in Settings lifts the reload and push budgets, as the WWDC25 session points out, which saves a lot of guessing.

Traps

  • Network in the provider. getTimeline may run while the app is suspended. Fetch in the app or a background task and write to the App Group; the provider reads local data.
  • Returning early from perform(). Launching a detached task and returning means the reload reads old data. Await the write.
  • Binding-based controls. Only Button and Toggle with an intent are interactive. A Slider or TextField will render but do nothing.
  • Opaque backgrounds outside containerBackground. The system can only remove a background it knows about. Put it in containerBackground(for: .widget).
  • Using a button to open the app. Apple asks that interactions do more than launch the app. For deep links use widgetURL(_:) or Link.

Checklist

Need Use Minimum
Predictable changes Timeline entries with .atEnd or .after(_:) iOS 14
App changed the data WidgetCenter.shared.reloadTimelines(ofKind:) iOS 14
Live countdown Text(date, style: .timer) iOS 14
Tap to act Button(intent:), Toggle(isOn:intent:) iOS 17
Pending state invalidatableContent() iOS 17
Tinted and clear Home Screen widgetRenderingMode, widgetAccentable(), widgetAccentedRenderingMode(_:) iOS 18 for images
Server-driven reload WidgetPushHandler, pushHandler(_:) iOS 26
Portrait extra large .systemExtraLargePortrait iOS 27

Before shipping, look at every family in light, dark, tinted and clear, with the largest accessibility text size, in StandBy, and with the device locked. The locked state is where interactive widgets most often surprise people: the button is visible but does nothing until Face ID succeeds.

Sources and further reading

Read next