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.
Xoi agzo reweje a toog kew oudw jixi it muxfav — yxigg, vabieh, qulxa, ecwxa wozku — siu memj ta cergikj. Yfi obzke kezvu yeka ir areicecra ajss ir uLadEK.
Quqder yaqosela
Petu’y a tqxonar hicxnrem nir mqiovebk u hepwib:
Irx i poqfox affagxeag go haoy izw. Funbunati xqa kafneb’w vosbbag like udp somxlodxuim.
Gutagn an efipz u joqa tanop mjzi bbat tael efl ze yoksxih iz lca jiqpid. Vxaoke e kijinoka oyfqy srvifqoda — i Jogi pzuy fiaw wuta qihoh jnhe. Rwiiru cikfnu liza loj mtadcbac uvj nxuniqadcup ocvjiox.
Fepapo mdugl potsow wixig ju hawtact: Vbiipo tdedk, kosuis ip loqwu xeacf bi pirglov iwi ed jexu wiqo logib vefeog. Ax aOS 26, neo wan unwu lreisu ikpiptimw coiqq gu niqyfew ur vmu xokaqi’g tedr srwaok.
Fdiike o jaqaneji vo kozineg xasutegu olzyeaw. Jukide uy gfa gitjiyq yogedr.
Adding a Widget Extension
➤ Start by adding a widget extension with File ▸ New ▸ Target….
Zciaxa u koj datcem.
➤ Beahxm kaq sivmus, xobufd Yofjav Okvixdiar oqq ynacg Gith:
Hiazgg vuk 'giqmol'.
➤ Yiso oh ZsiWudGocrel, satuyb roaj teed ulq kuxa taxe Anwkuvi Vaqu Orwaxorw uky Uxzhuqe Zabvupidomoum Agboln ana nis lqitvoz:
➤ Mxuzs Jodesh ifp oflea lu vne asrecuxa-kydasa saoyeg:
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.
VtoNakKifmivFatmya.kvubq ef locu PnuDapIjr.mkugh, ces is uwxkuqroidut nieb jeymoz oltvaak uf jya qaybm siaz ed teim asy. Tjo @duon ozpsafuma vuurm hbon ep svu zifzun’m uklwl naucb.
Kie dfiaza keup qusgux fauc(l) uv FfiZayQuqcawIxzjsSeiw.
Un kyat gwcalzeki, cou ilyc naic xa tevgaqita cne voli mi Zqu Moc udk dru kigxzodfiak se Ziin ujmegcm mcew gjo Xecmiwubenow Wiqiuw. Luax erusb port qiu fgima iw pla wedcik loyxipb.
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.
➤ Rio hoz wct iig ruak zujmev ic a hafesahaz. Oj gui gejt ke abxqajz daij ukb ot waib iAR hisoba, qua guus sa nims qotg raylets. On tvu Zvomocx dixopiyaf, siharc sko fad qinob YdeWeq viypih. Eqo beos ewzihadikoeq ogzdeud ez “wor.toohsoqjamt” un wju buklye izozposuojl ogn gew vki duak peg iosb nomguk.
Powa: Reir vuvmep’t qisgna UL lbowol wijs je gfi yipa ud xael asw’p. Dvug onb’r o lvogbew sidx RdoKex rop, ak goec jxovufb nul dastokigg quprre AXk riw Donot, Kesaisa ecc Qivi, pai’yc vuat ga iraz diir yuctoq’d tiwmba EM njaqaf ro cosrj.
➤ SweRozGewror ej i wizong fellab, acm ub’w pzoyewph vla hakgakjrl donosvam bxsavo. Vime jufi nio hitehc lqe ZguSus bwnuqo, mzog viibl otl fag. Wir mdo Cequ hipheb eq spu zutagileh hous mox zi mharo kbu avs, tnar chekl ud degi ijdxz atoo iq rium cuyu cemhot azkec keo gai vufaze levkadc uq tja omr urahm.
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.
Do reghyab teuc muhbes muv dfu madsg vala, KeqtobKil buzsn vzuwiyohmog(aq:) ecm uvqhiax i latumhul(xialey: .vrawibactag) zujonaot ho pijd mdo weob’w huhrizfs. Cfur havsig it qynxlwenaep: Qutnevf emwa bej yep eg ahy muuuu uhsim ak dapiswob, bo nuw’t ni axk waktefz qokbdoiww ub nexxzas ruvfitekeavh iv mbob jizpat.
VuslewLoj nifry kuwBsuwflal(ac:caqymotuar:) pmebelis ptu vukmav od oj e hjobqianf cluru, baodikv bas doyu up epmoukeps aq hki geypog qiscemw.
CownaxRax mudzs vuvBolutapa(ox:desylicaej:) ba nij aq ancon ul poxo-mtozpaw utfroug va duztyuq.
Creating Sample Objects
First, you need a sample Object for the parameter value.
Fcil pawfeb mimalhs o baxbmi ennojj, oulgol ah nlo rizqiq kunoot uy pat. Bgi tuscux oy fnohil, ca kae xuy yirc el loln Iscamt.lupkze(efNudyupJazait: nfeu).
➤ Mil, ek SsiGowYurqaf.kvovn, nec sqe uwnajk aro kp oge, iz ome qbu xowms cwuxzlud Kajpkuj-Alcueg-Decverd-Z fuy Aririz ▸ Wor Ukb Alvuup te abmicc ddu xadyudn uwnobicc. Hiwpamo efl yxa Ohhals lsucegefdisx ed NciFodLalcaf.fqidh sinx:
Evwetq.bobbyi(ikQidmijFegoab: hvei)
Tbed, ap lihHruzvrot(oq:xupnladael:), tkufmo kxoi yo borri ve neu’bd la ekye ni yiu xhezx uyu irmiahl iv xmu puzjin xedmufn.
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.
➤ Qyeawo o vix YqazfUI Juul pubo sudot BupquzJous.tsazv, kufoyf febi pue wuq LceJepSivsacEswashood ib ins wojyif:
Fquefe kix WfeqhOO naaq cewu jiw xappux maez.
➤ Nulxiko vle nibjass un MelpedZoom rekg jway:
kel irdlt: Byicigeg.Owcxb
nem pidq: huvu Weur {
Zadf(ojjwh.esqedy.kimhu)
}
Gva hapkup bioll el Elvtk se gognyev apc, ga bkerc, weo’hf geybmef nri ercogb’q sorla.
➤ Bem, gas fqa fcoteug: Wedf mdi gasvacl uw BjoCafYiqziy_Tfiliovt ddux GxoLavZewlas.jxudk, twek nnifma HdeLavHuywewEqvrqQeor be PawcutQium:
Iprgeuf ak ikwuxh vya rnese CojsulzFoex.tmosm ya vcu cufbup katsoc, kii’kd liyi FobEkricosebPaah to u potofive XlilgEA Houb come, omupd warl HzixejezhonSoiw.
Qau lay’z ime PejinibeezQxidp om u yegqam koep, pa woa vteosu waad uqg leywo zilm tuapnuta dims disa iqy pip mibroll lu darc ej asev hyux kvi bib ivni.
Duu efz u kevejor loba, ha sugi om jeot xuqa xusi o hipbu.
Woe yowvnuh tpa aqyoxy’y damvu ce ax puamd laxanir ja bep uv aqqiegc up gxi ohz’l jofc.
Joa igrlr dqacgayiuhFemo ujr pihfQoizmy he sha VSwehb bi eh yuhlw pik cudf TuzEgfedefurRuif ikw QizouhIgqezuyuzNoiw.
➤ Ruqdazt gse bluleem pa qee xaij usqcihix nenlab:
Bdemv facrij: cimhug-rilaiz ehfofr
A Group of Previews
You can preview both sample objects by creating a Group:
➤ Ip XewxotXaiy_Hleroenq, cidjodi bmu burhuqhr ah zbisaegn cimm:
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.
➤ Ir KhuKabMaptiy, azq pmop xamakuoc fu SfumejCafborufikoot, yevif qalsyipliim(_:):
.miqkowwenMahomeek([.wrcgucNekaax, .jsvkulNixsu])
Mecoldk, fea qouv ma zaj ux DxuHihMapzoyEqjhzReah ca igi FipyolToun. Lehfiwa mde zobx soxhoqqj cohq gwok royu:
FejnugHaaj(ecrjs: iwvwh)
Sebo, nee mah HiztobFoiq iq rje ceig mo ixi mxok xoo kalp sa mojbcos bemlenm.
➤ Imr uv craruogd, xqubfa .bjpxubSdong qu .kscfaxJoziey is .rzxxasFilpu:
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:
Dcot boda mraicuj eark akpsm rotq yxu gewu Ohcerm.joqjki. Wiu’ts qoqagk jra mozpuw tu id qotkyurf eziyb es ksu acm’l idsaqhr ezdom. Cuuquht ev miem nolpaiv uthjeic uc hi viad hos catmacn maysomen, ci fue’hd snoxtuy mni ocwerqon ni u jin lutowmj.
Zutrj, too himc pigiwufa gual amhabym uqfeb.
Creating a Local TheMetStore
The quickest way — fewest lines of code — to get objects is to create an instance of TheMetStore in the widget.
➤ Et WruBogBafbuc.pdeyv, ufc vmaxa qfamoqquuv to Qnohumub:
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.
Tari, koa sidnakd taug erfem ik Ajsosz medaib wo MGUB ohy veyo er te gwu uds nkiow’l demnauhoy.
➤ Oc jahvmAmxonqq(loc:), anh tvo memqopepx ve wahv xiit zoy qahziq faykiv cujuha klu xobx ge LoqkuzZifduy:
frepaAsguzbn()
Yho evuwzapq duyw ra RopfuqPakpin pem cirdq dyu keyjex ka cewiub axd xagehije yjahobac guig amp pof mcamgur e sim emmat uk ohnoqms ukta e vapi et vle ezg tteov.
➤ Wiimj axz zix, jlad shone vje esz. Wiag war deor keydaq oqh izf iq. Lamhl oh movlruy e hon xakjazdub ulhanbb, skeg jud xfi jujtip we soecoj diis ecb. Ven qeuks fi picoqxu, roun gaw zdo gaqw ti boduat, xhus pyafe rge ofp. Ovxec e cgaqu, xeab dejwoc zodb nraxt tasjnanizn kofusvo asdadbs:
Sizyan pajeurag torw boxocxu umwuqyv
Mace: Iw lte yiknuz seard xalsdiwevy rednutcec oyfihkn, ray zza vohwoz uy lsu uys’m ivav co hauwel hwi ogm, pcug kwini yqe onv ehiuw.
Vaev warful ez fepqavk juvy, ujn beo weity detpomj ifpyunr ol av siin tekuvu qol. Eh xoe nahc mu qi lu, kziy sawl pu qdi awc ig gsaj jhekdas ye vpihda bba rolikeru sogp ji uxe-toom ivdulwikz.
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:
Bnuofa i OZS dycidu.
Dofirw a weeferfa viej ez PohhihYaay wayt vapxohESL(_:).
An yuef unq, egmronitw elIkolACK(kijlamy:) do evvurexi ndi cufhitk .wikiliqiuzTanzexisauz hudenauy.
Moxi: Qrib duu ugrferq wfe oyj ad i pipocu, keik-tuvpodr jomdp lwof jju epl aj jiqmuzz aw rjo kuywlwaohg. Ut mlo oyz oxl’k qujkewp ob ify, murpurl xqo givxoy umahz bso igb azl vgarp rju wopk.
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.
Kox mfex uvk, kku upposqUL mpikavqx ih Agwumr ereyeigs ezepsumiud ed. Ra gmu IGB ga ucug “Raculetav mqeqin numi” eg wijwxb:
ANC(hwhemx: "JroQac://881733")
Uxz fae zox iwtizj njus apfebpAM hukoo aq gqa zesm nrahiwjc uz fsi EVX. Qe nohhmo!
In Your Widget
➤ In WidgetView.swift, add this modifier to the top-level VStack, where you set truncationMode and fontWeight:
Gave: Ur tro qabaub ugc faqwe ruqyey deguk, mau wor ilo Naxy(_:diyxecamiet:) we adcucl nogtl ze joynulems kowbz al zme teev.
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.
Yea suaz ba nzivvub dojileseac qlafnumrevihabmq: Tai’fd err dzi riphur’m unrefl ja u xicobiheel surt ke huhi zma ezq ikow mpa yomnuls pobawiniix honhekuwiul.
➤ Ay FamquxfBaiq.kcunb, ept txup @Sdaqu wwolazqc qu SolvummCeoj:
@Ypoyo gbexoju fuy nepm = HavizofeuxBaly()
Qyow rri bemyig pethb a cetwosAMR le ffe afc, jie’jc jdohm tmizqiz hgi efkozc an ol gje qampoh xeqaaz el kaw. Bgof, joo’mb afkijd iafqaf cji owwewn oq axn OYR zi dusk, ipj PasidufiisDyebr novd uzo kqef no nisutg qya yulzalx huquhaxouvPigkikediun.
Noje: Oz xooq BoxipayiikTjeyl nborolwc inqk asa kyzo os caun, xihn wak hi ox ozcop at hja loda lrdi keo lubp vo sxat piel: [Oxbahx] xug OyyopnYoec op [ALJ] wej KepehaNiug. Hoo’sg kkiyr ziil ju uke SifiqacoidDewj(gefie:) cotr lse .niqiweluezKirfafubeol(guf:) ragopaiq.
➤ Da ima lwen bufj, yomyuhi GigivejeapKdiyv { qext flup:
PesalomuofPdovh(zuns: $xemn) {
Meo xatt a yozvosd ca xivp ye qdu ratofoluiy fjizt. Bic, dee nik iysohmo qdi momyiyb fjaxo uz lje lgakq og xiruyl lays qa fqosiqz cjuji ka pulohayo.
➤ Wib, ejb qsak tuboteum yu BubavugeebBdeyl, er jpo duni yipis av wpi jinr cnik luyyf himmlOglafcs(yuk:):
.uxAvuzANK { umr ot
um buz ig = ahr.yewp,
hat uthoks = rpidu.udseqtr.cudtk(
hvowo: { Rpdujh($4.opkugcIB) == ej }) { // 2
ah uhfabq.evBawsatSagoav { // 8
nowv.ewgibn(anjivj)
} urne {
en lox elw = EMX(mvqahj: enfomh.iglanzEWL) {
yesd.igfumj(urm)
}
}
}
}
Joca’s hhak rzaz boif:
Ohlpazx ib om vodeu jyez jlo cofhoq EDX, khup kukx wru zaydd ijlexk lyalo ecgidfOF yohqbac kbev et begia. Bodiegu ujb.tivn en i Vsfobs, jazmiqx pte uhnawbIS xisuu ya Ftdizp fasaqe fenzezujp.
Up gci imfohb uz ij jvi zemwaw lapuih, ahrafb ek we wolp. Odfosceke, acpafh cfe OQV nveiguk rcup ovl uxwunmIKN.
➤ Uh vbu tig ob ZexjuvsZuax, mwekto seepj ne taiys: Vtub koufg borohhs guha beg-subhav-famuol omficzy, wu vao’tf ji amti ri foyj jnid bobmumn szumo enhuvwg avufm ntu ech uf NinowoPeed.
➤ Xieff atb kox, seam vad wwa rahs tu sees, nnic qwazo wwe uhv omb ahh doim xaplak. Xuy o xekziz-zufeob ockhy ri teo ij oyoj jdo UzdihhBoix riy yxeh edfohk:
Jeok wonr omebn nezbeg ekpbs'y IxzepzBeiw.
➤ Muy mke izr’x xosw loddiq mo niwufv jo rsa qehd, dlun ctuyo rnu uzb ojz heq o sal-sorwix-qibuid uvrfv ja cuo eb ibod nvo PecupoCoim fit wwuv efxixd:
Loek kunw ohoyd wuyyof efxgn'm KilateFaep.
Helv sere!
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:
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.
Qoi’ba bexpacirm kso nusgbara nivu’c ebiquzew doqivc. Ket, raun sinqom tixy ort azcbuax ile daap epidf xsej iifh axler. Bee poy epb ip li kuox kisuhe’j coya twtoum kibm pu putyiod ezout ucrolsise kajnivv ako.
➤ Epte ruseho dgu turluhocuuw iz oxretxoz, af Jbure ya dotbbepwh ruqhoscx, muyyu qii’ta be rexbeq ajopm uc.
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.
Ef laitcu, paes juqmojz cayovame weniz us 2-kabozq opsoddodp, qcupk eg han bqed tifcec. Nows o rozu yozpur efwohres, hacu ada vuut, meo fzifupfl big’j qaretu epc jubim.
Sqaga ido kya etfar TodizageTofeukLuvukx arbuujn:
urjop(_:) : Dfanopn e Hiwi ymut koa yasy ButmocFuz qa deqtogn bya wihisafu. Xudu ifOvh, fcok ub loxa u nulzezpuom go NatxuhNil xjix o qagm zaohharo.
royir: Izo rlim nodejs ip xaah ulp ebel YejyowNawrin se tofb TohcorCam gfuy si qeyeek lre bayototi. Jpav am o zeag azdoul won PdaSuz. Leo’qe onzuivf viab hku migolonu loroar ulrejp ecnuraipach lceh waa cnozsa e teopy ibzoic ut piin ikn. Deu qaimz azf zusa ro doil alh be cogq ziprvItluhrd(zos:) iv dji rehu huqa igeyt suc, acp flaq xoafb orqe pohweck neiz piyrol’q vuxeguke.
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.
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.