Chapters

Hide chapters

SwiftUI Apprentice

Third Edition · iOS 18 · Swift 5.9 · Xcode 16.2

Section I: Your First App: HIITFit

Section 1: 12 chapters
Show chapters Hide chapters

Section II: Your Second App: Cards

Section 2: 9 chapters
Show chapters Hide chapters

25. Widgets
Written by Audrey Tam

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Ever since Apple showed off its new home screen widgets in the 2020 WWDC Platforms State of the Union, everyone has been creating them. It’s definitely a useful addition to TheMet, providing convenient and quick access to objects listed in your app.

Note: The WidgetKit API continues to evolve at the moment, which may result in changes that break your code. Apple’s template code has changed a few times since the 2020 WWDC demos. You might still experience some instability. That said, Widgets are cool and a ton of fun!

Getting Started

▸ Open the starter project or continue with your app from the previous chapter. In ContentView, change the store initializer:

@StateObject private var store = TheMetStore(12)

You further reduce the number of objects returned, to reduce the number of calls to getObject(from:), because you’ll be making a lot of calls during this chapter.

WidgetKit

WidgetKit is Apple’s API for adding widgets to your app. The widget extension template helps you create a timeline of entries. You decide what app data you want to display and the time interval between entries.

Adding a Widget Extension

➤ Start by adding a widget extension with File ▸ New ▸ Target… or by clicking + in the Targets section of the project window.

Configuring Your Widget

A new target group named TheMetWidget appears in the Project navigator. It contains two Swift files.

Doing a Trial Run

The widget template provides a lot of boilerplate code you simply have to customize. It works right out of the box, so you can try it out now to make sure everything runs smoothly when you’re ready to test your code.

Creating Entries From Your App’s Data

It makes sense for your widget to display some of the information your app shows for each object, using the properties in Object.swift.

Adding App Files to the Widget Target

➤ In TheMetWidget.swift, find SimpleEntry. Between date and emoji, add the following line:

Provider Methods

Adding the object property to SimpleEntry causes errors in Provider because it creates SimpleEntry instances in its methods placeholder(in:), getSnapshot(in:completion:), getTimeline(in:completion:) and also in the preview. Provider methods are called by WidgetKit, not by any code you write.

Creating Sample Objects

To fix the errors, you need a sample Object for the parameter value.

Creating Widget Views

When you’ve decided what data to display, you need to modify TheMetWidgetEntryView to display it. It would be nice to display the primary image of an object in your widget view, but AsyncImage(url:) doesn’t work in a widget, so you’ll simply display the object’s title.

Using App Views & Assets

Now, to make it look more like the app’s list view, you’ll need the WebIndicatorView from ContentView.swift and the metBackground and metForeground colors defined in Assets.

Supporting Widget Sizes

If you think one of the sizes looks best, or if you definitely don’t want to support one of the sizes, you can restrict your widget to specific size(s). For TheMet, long titles look better in the medium or large size.

Providing a Timeline Of Entries

The heart of your widget is the Provider method getTimeline(in:completion:). It delivers an array of time-stamped entries for WidgetKit to display. The template code creates an array of five entries one hour apart:

Creating a Local TheMetStore

The quickest way — fewest lines of code — to get objects is to create an instance of TheMetStore in the widget.

Creating an App Group

Xcode Tip: App group containers allow apps and targets to share resources.

Reloading the Widget’s Timeline

Next, you’ll set up TheMetStore so it tells the widget to reload its timeline whenever fetchObjects(for:) finishes downloading and decoding an array of objects.

Writing the App Group File

➤ At the top of TheMetStore.swift, just below the import WidgetKit statement, add this code:

Reading the Objects File

➤ Open TheMetWidget.swift.

Deep-Linking Into Your App

➤ Remove the widget from your device.

Creating a URL Scheme

“URL scheme” sounds very grand and a little scary but, because it’s just between your widget and your app, it can be quite simple. You’re basically creating a tiny API between widget and app. The widget needs to send enough information to the app so the app knows which view to display. Formatting this information as a URL lets you use URL or URLComponents properties to extract the necessary values.

In Your Widget

➤ In TheMetWidget.swift, in TheMetWidgetEntryView, add this modifier to the top-level VStack, where you set truncationMode and fontWeight:

In Your App

In your app, you implement .onOpenURL(perform:) to process the widget URL. You attach this modifier to either the root view, in TheMetApp, or to the top level view of the root view. For TheMet, you’ll attach this to the NavigationStack in ContentView, because the perform closure must assign a value to a @State property of ContentView.

A Few Last Things

A couple of housekeeping items before you go.

Organizing TheMet Group

➤ Organize your app files by grouping them into Model, Networking and Views folders:

Using Normal Timing

You’ve been using a three-second interval in your timeline to make testing simpler. You definitely don’t want to release your widget with such a short interval. If you want to use TheMet on your device as a real app, set up the timeline to change every hour instead of every three seconds.

Refresh Policy

In getTimeline(in:completion:), after the for loop, you create a Timeline(entries:policy:) instance. The template sets policy to .atEnd, so WidgetKit creates a new timeline after the last date in the current timeline. As you saw when the widget was downloading a small number of its own objects, the new timeline doesn’t start immediately.

Key Points

  • WidgetKit is still a relatively new API. You might experience some instability. You can fix many problems by deleting the app or by restarting the simulator or device.
  • To add a widget to your app, decide what app data you want to display and the time interval between entries. Then, define a view for each size of widget — small, medium, large — you want to support.
  • Add app files to the widget target and adapt your app’s data structures and views to fit your widgets.
  • Create an app group to share data between your app and your widget.
  • Deep-linking from your widget into your app is easy to do.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now