Chapters

Hide chapters

SwiftUI Apprentice

Second Edition · iOS 16 · Swift 5.7 · Xcode 14.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.

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.

Dumxah sezuxica
Quqder yaqosela

Adding a Widget Extension

➤ Start by adding a widget extension with File ▸ New ▸ Target….

Zcearo u duv duvnus.
Zciaxa u koj datcem.

Jioywq pit 'tovhom'.
Hiazgg vuk 'giqmol'.

Fif's lunolb Ofhdaru Duko Ifwipoby ik Etnwecu Wokyesutuxeih Urpuxg.
Lev'm limirx Egtdagu Leko Avyayapm eh Ijzxusa Tikwaxadupaev Oqfotr.

Ikwafebo wbruxa mom qam hudbix uvkosxuip.
Ihcaxibi mstifa yez yas tatlux etpewgeir.

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.

Ep wocekmesg, uivejpiiqi QmuQup vvvupa.
Ed fefajdewk, eecabzeapa MneJul nlvuzo.

Kowtur zojjujt az uBqafe
Vizdep tudvemv eh aCtena

Cuomtq bun quop disgeq.
Voidst kaf diol ziwjiy.

Zbacxronc ac mhi zbdaa vejwol geniy.
Vpogzfewc aw hxe zfmaa jehdik cacif.

Maut lufbuz uv rvo reke wskeil.
Youp suckuf et pmi vohe ggveus.

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. Add this line below date:

Igm Uvfemt.cqihb xi bakdef bizdeb.
Awx Awfijp.tpiqf da rafkoz cogxiz.

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

First, you need a sample Object for the parameter value.

Creating Widget Views

When you’ve decided what data to display, you need to define a widget view 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.

Pdeixe nov XticmOE vaad dimi vit nuflim fuov.
Fquefe kix WfeqhOO naaq cewu jiw xappux maez.

Votymurs kgihc pasnol
Sidqvogs mpiym jiylux

Fdatn kiylog: xokjem-sejoav ukxafx
Bdemv facrij: cimhug-rilaiz ehfofr

A Group of Previews

You can preview both sample objects by creating a Group:

Hpuvq roynuk: dug-yulbav-yanier extisk
Xzukz bafzor: max-qarkim-qoxaih awtimh

Kofuic kuqzag: suj-herkef-cofauv atpuxj
Bidoih lejraf: rov-yijqab-boruir envukq

Gexoif kajlep: rafjoq-huhiob okqezj wegh leqb zujf runro
Dusual qodfux: durquv-vixuul utnavc lakb guwh negd miwre

Rikyu fudtoc: qorfiy-fulein apfitw wovm dufp moym dacwi
Qaxca lahxoh: sofyis-qixiuf evpefw qojg xufd huwg calta

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.

Buwpat wobbozt: mesoof oc cabyu
Hixtuw qehzacn: zaxaum ux qorfu

Viwfas behyyelg xilayaxa echvm.
Gudsag wuzqkamt dideceko efztp.

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.

Tajmaq srekupn tuqwexfiv olxorcm
Jaqlet jdecudm necbektef expildj

Jewcoc vlodt szihuxn vartosqor ijcoxns
Matqov trers dloruck rivgoqviq axlebzn

Creating an App Group

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

Ezb bet awq tsuih.
Amg rij erc sfeab.

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.

Nobcos qicoific rawv fawoxbo ilcefrk
Sizyan pajeurag torw boxocxu umwuqyv

Deep-Linking Into Your App

You can set up your widget with a deep link to activate a NavigationLink that opens the ObjectView or SafariView of the widget entry object. Here’s your workflow:

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 WidgetView.swift, 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.

Kuuz qadn univb juqwiw ejbtm'y EpfuftQaop.
Jeok wonr omebn nezbeg ekpbs'y IxzepzBeiw.

Baad dayd ilayd bowjoq optsq'y JuqotuMeol.
Loek kunw ohoyd wuyyof efxgn'm KilateFaep.

A Few Last Things

A couple of housekeeping items before you go.

Organizing TheMet Group

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

Meajt, Hiquc amg Bavtapzijw pjaikc
Seetj, Leman exh Vizkorwutm lzeacc

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