iOS Widgets & Extensions

iOS Widgets and Extensions

iOS Home Screen Widgets allow users to see vital app information at a glance, without opening the application.

Introduced in iOS 14, Widgets are built entirely using SwiftUI and the WidgetKit framework.

Widgets are not mini-apps; they are meant to be fast, glanceable snapshots of your app's current state.


The Timeline Provider

Unlike regular apps, widgets do not run continuously in the background.

Instead, you provide iOS with a "Timeline" of data points and tell the system exactly when to update the widget.

For example, a weather widget might provide an array of 5 temperatures, each scheduled to display at the top of the next 5 hours.

Basic Timeline Entry:

import WidgetKit

// This struct represents a single frame of data in time struct SimpleEntry: TimelineEntry { let date: Date let currentScore: Int }

iOS wakes your extension briefly to fetch this timeline, then puts it back to sleep to preserve battery life.


Building the Widget View

Because widgets are purely built with SwiftUI, rendering the UI is incredibly familiar.

You simply create a SwiftUI view that accepts your TimelineEntry as a parameter.

Widget SwiftUI View:

import SwiftUI

struct ScoreWidgetEntryView : View { var entry: SimpleEntry var body: some View { VStack { Text("Live Score") .font(.headline) .foregroundColor(.secondary) Text("\(entry.currentScore)") .font(.system(size: 40, weight: .bold)) } // Widgets require a container background in modern iOS .containerBackground(Color.blue.gradient, for: .widget) } }


Interactive Widgets (iOS 17+)

Historically, tapping anywhere on a widget would simply launch the host application.

However, starting in iOS 17, Apple introduced Interactive Widgets.

By using App Intents, you can now add functional toggles and buttons directly to your widget!

This means users can check off a to-do list item or play a podcast directly from their Home Screen.


Other App Extensions

Widgets are just one type of App Extension. Apple provides many others, such as:

Extensions run in a completely separate process from your main app, requiring careful data sharing using App Groups.


Exercise

Which UI framework is exclusively required by Apple to build the user interface for iOS Home Screen Widgets?