Build glanceable widgets with WidgetKit and timeline providers.
WidgetKit Overview
# Framework: WidgetKit
# Import: import WidgetKit, import SwiftUI
# Target: Add Widget Extension target
# iOS 14+, macOS 11+, watchOS 9+Adding Widget Extension
# Xcode: File → New → Target → Widget Extension
# Name: MyAppWidget
# Include Configuration Intent: No (for static) / Yes (for configurable)Basic Widget
import WidgetKit
import SwiftUI
// Entry - data for a single timeline entry
struct SimpleEntry: TimelineEntry {
let date: Date
let message: String
}
// Provider - generates timeline entries
struct Provider: TimelineProvider {
// Placeholder for preview
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(), message: "Loading...")
}
// Snapshot for widget gallery
func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> Void) {
let entry = SimpleEntry(date: Date(), message: "Hello Widget!")
completion(entry)
}
// Timeline - when to update
func getTimeline(in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> Void) {
var entries: [SimpleEntry] = []
let currentDate = Date()
// Update every hour for 24 hours
for hourOffset in 0..<24 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = SimpleEntry(date: entryDate, message: "Updated at \(entryDate.formatted())")
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
// Widget View
struct MyWidgetEntryView: View {
var entry: Provider.Entry
var body: some View {
VStack(spacing: 8) {
Image(systemName: "star.fill")
.font(.title)
.foregroundColor(.yellow)
Text(entry.message)
.font(.caption)
.multilineTextAlignment(.center)
}
.padding()
}
}
// Widget Configuration
@main
struct MyWidget: Widget {
let kind: String = "MyWidget"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider()) { entry in
MyWidgetEntryView(entry: entry)
}
.configurationDisplayName("My Widget")
.description("Shows a simple message.")
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}Configurable Widget (App Intent)
import AppIntents
import WidgetKit
import SwiftUI
// Configuration Intent
struct WidgetConfigurationIntent: WidgetConfigurationIntent {
static var title: LocalizedStringResource = "Configuration"
static var description = IntentDescription("Choose what to display")
@Parameter(title: "Message", default: "Hello")
var message: String
@Parameter(title: "Show Date", default: true)
var showDate: Bool
}
// Entry with configuration
struct ConfigurableEntry: TimelineEntry {
let date: Date
let configuration: WidgetConfigurationIntent
}
// Provider
struct ConfigurableProvider: AppIntentTimelineProvider {
func placeholder(in context: Context) -> ConfigurableEntry {
ConfigurableEntry(date: Date(), configuration: WidgetConfigurationIntent())
}
func snapshot(for configuration: WidgetConfigurationIntent, in context: Context) async -> ConfigurableEntry {
ConfigurableEntry(date: Date(), configuration: configuration)
}
func timeline(for configuration: WidgetConfigurationIntent, in context: Context) async -> Timeline<ConfigurableEntry> {
var entries: [ConfigurableEntry] = []
let currentDate = Date()
for hourOffset in 0..<24 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
entries.append(ConfigurableEntry(date: entryDate, configuration: configuration))
}
return Timeline(entries: entries, policy: .atEnd)
}
}
// View
struct ConfigurableWidgetEntryView: View {
var entry: ConfigurableProvider.Entry
var body: some View {
VStack(spacing: 8) {
Text(entry.configuration.message)
.font(.headline)
if entry.configuration.showDate {
Text(entry.date, style: .time)
.font(.caption)
.foregroundStyle(.secondary)
}
}
.padding()
}
}
// Widget
@main
struct ConfigurableWidget: Widget {
let kind: String = "ConfigurableWidget"
var body: some WidgetConfiguration {
AppIntentConfiguration(kind: kind, intent: WidgetConfigurationIntent.self, provider: ConfigurableProvider()) { entry in
ConfigurableWidgetEntryView(entry: entry)
}
.configurationDisplayName("Configurable Widget")
.description("Customize the message and date display.")
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}Widget Families
// Different layouts for different sizes
struct FamilyWidgetEntryView: View {
@Environment(\.widgetFamily) var family
var entry: Provider.Entry
var body: some View {
switch family {
case .systemSmall:
SmallView(entry: entry)
case .systemMedium:
MediumView(entry: entry)
case .systemLarge:
LargeView(entry: entry)
case .systemExtraLarge:
ExtraLargeView(entry: entry)
case .accessoryCircular:
CircularView(entry: entry)
case .accessoryRectangular:
RectangularView(entry: entry)
case .accessoryInline:
InlineView(entry: entry)
@unknown default:
SmallView(entry: entry)
}
}
}
// Small: compact info
struct SmallView: View {
var entry: Provider.Entry
var body: some View {
VStack {
Image(systemName: "house.fill").font(.title)
Text("Home").font(.caption)
}
}
}
// Medium: more content
struct MediumView: View {
var entry: Provider.Entry
var body: some View {
HStack {
VStack(alignment: .leading) {
Text("Title").font(.headline)
Text("Subtitle").font(.caption).foregroundStyle(.secondary)
}
Spacer()
Image(systemName: "chevron.right")
}
.padding()
}
}
// Large: rich content
struct LargeView: View {
var entry: Provider.Entry
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Dashboard").font(.title2).bold()
Divider()
HStack {
StatView(label: "Items", value: "42")
StatView(label: "Completed", value: "28")
StatView(label: "Pending", value: "14")
}
}
.padding()
}
}
struct StatView: View {
let label: String
let value: String
var body: some View {
VStack {
Text(value).font(.title).bold()
Text(label).font(.caption).foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
}
}
// Lock Screen widgets (iOS 16+)
struct CircularView: View {
var entry: Provider.Entry
var body: some View {
ZStack {
Circle().stroke(.gray.opacity(0.3), lineWidth: 4)
Circle().trim(from: 0, to: 0.7).stroke(.blue, lineWidth: 4)
Text("70%").font(.caption).bold()
}
}
}
struct RectangularView: View {
var entry: Provider.Entry
var body: some View {
VStack(alignment: .leading) {
Text("Next Meeting").font(.caption).foregroundStyle(.secondary)
Text("Team Sync").font(.headline)
Text("2:00 PM").font(.caption)
}
}
}
struct InlineView: View {
var entry: Provider.Entry
var body: some View {
Text("Next: Team Sync at 2:00 PM")
}
}Timeline Policies
// Update policies
Timeline(entries: entries, policy: .atEnd) // Reload when entries exhausted
Timeline(entries: entries, policy: .after(Date())) // Reload after specific date
Timeline(entries: entries, policy: .never) // Never reload (manual only)
// Smart updates based on conditions
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
let entries = generateEntries()
// Update more frequently during business hours
let now = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: now)
let policy: TimelineReloadPolicy
if (9...17).contains(hour) {
policy = .after(calendar.date(byAdding: .minute, value: 30, to: now)!)
} else {
policy = .after(calendar.date(byAdding: .hour, value: 1, to: now)!)
}
completion(Timeline(entries: entries, policy: policy))
}Dynamic Data (Network/API)
struct DataEntry: TimelineEntry {
let date: Date
let items: [WidgetItem]
let error: String?
}
struct WidgetItem: Codable {
let id: String
let title: String
let value: String
}
struct DataProvider: TimelineProvider {
func getTimeline(in context: Context, completion: @escaping (Timeline<DataEntry>) -> Void) {
Task {
do {
let items = try await fetchWidgetData()
let entry = DataEntry(date: Date(), items: items, error: nil)
let nextUpdate = Calendar.current.date(byAdding: .minute, value: 15, to: Date())!
let timeline = Timeline(entries: [entry], policy: .after(nextUpdate))
completion(timeline)
} catch {
let entry = DataEntry(date: Date(), items: [], error: error.localizedDescription)
let nextUpdate = Calendar.current.date(byAdding: .minute, value: 5, to: Date())!
let timeline = Timeline(entries: [entry], policy: .after(nextUpdate))
completion(timeline)
}
}
}
func fetchWidgetData() async throws -> [WidgetItem] {
let url = URL(string: "https://api.example.com/widget-data")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode([WidgetItem].self, from: data)
}
}Deep Linking from Widget
// Handle tap with URL
struct WidgetEntryView: View {
var entry: Provider.Entry
var body: some View {
Link(destination: URL(string: "myapp://detail/\(entry.item.id)")!) {
WidgetContentView(entry: entry)
}
}
}
// Handle in App
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL { url in
handleDeepLink(url)
}
}
}
func handleDeepLink(_ url: URL) {
// Parse and navigate
guard url.scheme == "myapp" else { return }
// Navigate based on url.path
}
}
// Or use Intent for interactive widgets (iOS 17+)
struct ToggleIntent: AppIntent {
static var title: LocalizedStringResource = "Toggle Item"
@Parameter(title: "Item ID")
var itemId: String
func perform() async throws -> some IntentResult {
// Update data
try await DataManager.shared.toggleItem(itemId)
return .result()
}
}Widget with Core Data / SwiftData
import SwiftData
struct SwiftDataEntry: TimelineEntry {
let date: Date
let todos: [Todo]
}
struct SwiftDataProvider: TimelineProvider {
let container: ModelContainer
init() {
let schema = Schema([Todo.self])
self.container = try! ModelContainer(for: schema)
}
func getTimeline(in context: Context, completion: @escaping (Timeline<SwiftDataEntry>) -> Void) {
let context = container.mainContext
let descriptor = FetchDescriptor<Todo>(
predicate: #Predicate { !$0.isCompleted },
sortBy: [SortDescriptor(\.createdAt, order: .reverse)]
)
do {
let todos = try context.fetch(descriptor)
let entry = SwiftDataEntry(date: Date(), todos: Array(todos.prefix(5)))
let timeline = Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(300)))
completion(timeline)
} catch {
let entry = SwiftDataEntry(date: Date(), todos: [])
completion(Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(60))))
}
}
}Testing & Debugging
// Preview in Xcode
#Preview(as: .systemSmall) {
MyWidget()
} timeline: {
SimpleEntry(date: Date(), message: "Preview")
SimpleEntry(date: Date().addingTimeInterval(3600), message: "Hour later")
}
// Debug: Force timeline reload
// WidgetCenter.shared.reloadTimelines(ofKind: "MyWidget")
// WidgetCenter.shared.reloadAllTimelines()
// Get current widget state
WidgetCenter.shared.getCurrentConfigurations { result in
switch result {
case .success(let widgets):
for widget in widgets {
print("Widget: \(widget.kind), Family: \(widget.family)")
}
case .failure(let error):
print("Error: \(error)")
}
}Best Practices
# WidgetKit Best Practices
1. **Lightweight**: Widgets run in separate process with memory limits (~30MB)
2. **Fast**: Timeline entries should be pre-computed, not computed on-demand
3. **Efficient**: Use .after() policy, not .never with manual reloads
4. **Relevant**: Show glanceable info, not full app UI
5. **Adaptive**: Support all widget families your widget makes sense for
6. **Accessible**: Test with VoiceOver, Dynamic Type
7. **Privacy**: Don't show sensitive data on lock screen
8. **Battery**: Minimize network calls, use background tasks for heavy workTry It
Add Widget Extension target. Create timeline provider. Support multiple families. Add deep linking. Test in widget gallery.
# Xcode → File → New → Target → Widget Extension
# Run widget extension target to testBuild widgets
- Create static widget with timeline
- Add configurable widget with App Intent
- Support all widget families (small, medium, large, lock screen)
- Fetch data from API in timeline
- Add deep linking to app
- Test with WidgetCenter reload
- Add SwiftData integration
WidgetKit uses timeline-based updates. Provider generates entries. Support multiple families. Use Link for deep linking. App Intent for interactive widgets. Keep widgets lightweight - no heavy computation in timeline.
Resources
- WidgetKit: https://developer.apple.com/documentation/widgetkit
- App Intents: https://developer.apple.com/documentation/appintents
- WidgetKit Tutorial: https://developer.apple.com/tutorials/swiftui/building-widgets