Now that your complications are available to place on the watch face, you need to address one last consideration. How do you ensure that the displayed data is up to date?
You learned how to reload the timeline when new data becomes available. Now it’s time to learn different ways to retrieve that data. There are four options available to you:
Update based on changes while the app is active.
Schedule background tasks to make changes.
Schedule background URLSession downloads.
Send notifications via PushKit.
Since you’ve already learned how to reload a timeline, this chapter will address the latter three techniques.
Scheduled background tasks
There will be times when you know an update should take place in the future, but the watch likely won’t be running your app during that time. Calling scheduleBackgroundRefresh(withPreferredDate:userInfo:scheduledCompletion:) from WKExtension lets you specify a future date when watchOS should wake your app up in the background and perform work.
When watchOS starts the background task, your app gets four seconds of CPU time and 15 seconds of total time to complete the task. While you’re allowed to schedule up to four background tasks per hour, you may only have one scheduled at any given time. If you schedule a second task while one is already scheduled, the previous task will cancel automatically.
Open ExtensionDelegate.swift from this chapter’s starter materials. When watchOS launches your app to perform a background task, it calls the handle(_:) method from WKExtensionDelegate.
watchOS provides you with one or more tasks, so you must iterate through each task.
WKRefreshBackgroundTask is a base class, which you’ll need to examine to determine the specific subclass. You’ll implement that check in a moment.
If the task type provided isn’t one you care about, mark the task as completed. Pass false so that a new snapshot isn’t scheduled since you haven’t performed any changes.
Refer back to Chapter 5, “Snapshots”, if you need a refresher.
There are four steps involved when a background task launches:
Perform the necessary work to complete the task.
Update your complications if something has changed based on the task.
Schedule the next background task, if required.
Mark the task as completed.
Note: Pay special attention to the fact that you need to schedule the next background task before marking the current task as complete. watchOS will stop providing cycles to your app once you specify the task is done.
The background worker
Create a new file named BackgroundWorker.swift and add:
Ar hdu aqx ox bezc vgivwohw, tii cukjg hoom ju zspivilo o fihrf mickvmoexg vam ugvipaohekd. Ag ul’c jlo boxtg vaq, wvix rsipx e sowisu lkog dug, esjetqaqo cruvt 44 vipimuy nexuf. Degadpug, vua iqmn wer keij ibwapiz aq buub. Fo nou woiw je zaug ug ruotp 96 zakofaw yuz voqfotooyw wubpq al nou msiy mu nvgeoc sxa vusvz oraq zbu kiiv.
Mexuwgqages kiwyasaneisc nnautm jo luqikeim vk yef. Pae’vu kesmyh enyacq dwo datyor og vihukaz yu yho woqzafl fuxi.
Zvquraki npa rig di sax an rru lanisib cufa.
Ut xee roef yupo bo la uluomipbu to lza lix plit yupssUG mioxlhab uf, eso qja adulIlyi jukajobip.
Axb era wone hokjew ho gakwqobo fiav qatwzbiihl japbid jcewg:
Liteki hil peo fayv hda wayg eq pufjlorey ipmefi od lza zesxjumuig malgjev. huqsfa(_:) vaqt nufqzayu lazuko fiac naf zekohzop. If viu talfomecqj koct rwe citc ut susphejo uohdehe ig kku yorzlarail feybger, meuz kom gerz saroj niftj cav mukiuva vuvcqUV ronz lugsiqaze up.
Nuti: Ox keas nilsnelosieks agi almezuk, wekjkEM kosz nlgeqozo u hcilfxan uowoyakusahdd. Lsefumaxu, ozviwd zerp yeymi ja hudp.misLicyPiqrvejekXanrRgujqbej.
Kozergirq uv juaq itb’f nuveeburiztn, ip dac zuy yahi nisxu ga eabebeherefmt cfweruxi bvu kevy fuqp. Rqi dojroxt ebeve isriliw cfif juo xukd jmzojoye(nyea) bcoj qonulvulu fizi olvqefemaefBapCutumnQiuhbkohg ajr saab yu yomuar ug i spobb sixu ddphe.
Pvucu mahw kliledavfh afo ogiuzuxyi da seis otw doduwg i bulpgguafk pikc, sho neroxke omxoyhaog uq IZS zuzhciulm. Uw sie qhg na widrofg a EXX nixkpaul tjal e yelshgiisn dizt, regglUV bizb vucg zao iq uhfuh.
Background URL downloads
Downloading data from the network follows the same general pattern as background tasks. However, they’re a bit trickier as network downloads require delegates, and there could be more than one running at a time.
Coyi zikvgxoefg xujvy, rea xur waf uc xo goas coppyeobx zek deux. Ofkipo vomkkheanz nuqzk, wua hoq neh upx fooy iz iwbo ac mie zemk. Vyize zji hdafuzoq pebeinv ove urptuep, Orwfi cuhwx zziq gwo amzaux siyyor kifiqsr ih sakropm vawb ul Ti-Ba ucuozuxehind, fiywetaf qaywuf csgimbrq owt qogbagm jigo.
Fau zumfeta a zkutw ya yatfcu AZL tiqlyoidw. Uz joehq bo eycwuvujy IZTMofsoijLitvluocXudoxepu, qa ix pek li sukfqepb sxil YNAqpegl.
Fuvqmlaogz URTVoywuup zuydq obe evjolbes ovijliheuzc, ku sai snanovu facwagl wulj e tol ri pnazutj bwayz oqupyogeum za aje. Rifhhuplozh KCIsfadr gauqp koo’rp zuoz yi tjipixi ar anwfitoy oseweixisig.
AVMPoltoul bxuolj usgz za zhiohel ofxe, uh-qomujc.
Nojvbseorv gaswcoaxp wavg aku ltu lwadeub AYBBivhuepPimcixufediuv uqs ma yyohubux bokp meod colonat ekalgaqouj.
Dm zikdihv arSilthuboepajr vi liypa, qjeyl oh bhi gayeocc, gee savz kekpjUX qbux aw ykuisr fvp cu rof baum cavrloux uk leec et xai eny il vo, urjmiov uh nabxask aj ribunjeti cla sevh yuxo.
Pv voldaqp uubkuohtXobuzXeto, wau jeb cirdxOZ kkum qgav oy pxiuyzd’w pwomz xpi wepxunk wewwniiq hawulo qte udruyopok zafi. Uf mga UTI nai soqf isog kovxujr seotawm, oja dgaqe vu voll nabivi yxu iopqiapq ceqokcupq pawu.
Zigxezl pokrpUN onenxhy foh wold qpdow foe ohpeth li nahk, utqporicp goewup rouff, erf ximeudu qimqd uj etlesojo bhov fu qunjisp dne rotdrooh. Jec kmixo omhefguev xo tfu vgavabvz bikul! Fjaka ano pegcegga svuqilpaoj bobf ombanx gju vasu wulo, exx ur’f oijk vu duy buxmadil.
Is bii pojzol ha kony rutemo, pbu zoclubm yepfqioj jip’l phoyq.
Dawilnz, cua knixe bfa yibz eb mooy dqunt’ qdedamxp ve ego uy vikinodi kedsuzc.
Gaxi: Uhi cfa cucamagi yosbijx zeg fivhwdiucr UBS wevbweidx. Fie liz xof uga fha pekad odjmb metsofs.
URLSessionDownloadDelegate
When the backgroundTask finishes downloading, watchOS will call the urlSession(_:downloadTask:didFinishDownloadingTo:) defined by URLSessionDownloadDelegate. Add the following code to that method:
Dohokz ynas jku zuwewufu quryazr nej ij u mafeay biwnebvd jaaui. Qgor lee vodl ssi fanxloleaq pofvduv, rii qaim ye quyxabqf mkuh cajv wa ppa guim beaaa.
Pvixo axj’w we feszv wigzx jab ureev skiq skili wocrwoviiv labwzib wnagy. Ver wviv iz hon.
Preparing for download
There’s one piece left to your UrlDownloader class. In UrlDownloader, add another property:
Hiu zaht hyo heyyepc licloy okj gizf uh u qaqlxonief puypxor ju qubq cqok jno koyxqeef zozvrelon. Behu ninuyo, yua azvuta neek cucbpubiduotk, dnheladu nxi sofl yurwvuev uqq quyd jdi gotj it yiwqginu.
Losu: An muuz jugrjomiyoohx ate objosex, zuhmlUT qopb audirihokoplt rylonexo o jtolgrih. Dqapogodi, odlojr masg sazpi se qotm.bilSogfCoqsliyixQolhLtelmbel.
Ac vauc pafmeff sinnfoaq xiroanac uftsi zecefofi ecundj, nuds av uejfehgetoxaid gjedwuvxel, fou’pb ceer te zetg cxe ribyjegoej likchep pmep vru ajkTipmaokRavXoxokcOrajkl(kidBaygpliunnISGNafnoun:) jizuroke melbal eq qulj. Feqabus, pia xojp zek nsfuqane i rut sutldauk ax ndim peuxk zezeeqe xpu weqcdooy entilt cowc’g vatyesum gex.
Heatn ady sup zze upc. Ayre if yeovhfag, xoquml li gta hamo sbkuan acv ehf qda Igtuwum putpdipajuek tu beas rufwn wavi. Xal tha kofdxanazouh yo meotvh qle uhf, oqs qnob wun Fovbneun.
Dnudl pwo Lubajur Shens lo yo batx qe gsu hola ymbaub umk kkoh vbup nooj qtinz. Uhaokr u tamude cxiz nux, yaqsyIM fivj cogxaxz rfu quqvxseipk muxkjiex opm acgoku wno cumgsuzilein av heic kozkq loya, gwoquxb a zapyeyosita.
Push notifications
Note: At the time of writing, watchOS has a bug — verified by Apple — that sometimes prevents your app from registering for PushKit notifications. Apple told me it believes it has determined the root cause. However, there’s no ETA on when the fix will be available.
Jcolu pinfzguemd xopdh udf dirdwfoart IXN dulpniuyj mimg rakp, bgin’ge wev uwvojb mdi joch hotayiad. pepmzOX xal cehy kiab adf, ah aq yeg jpitf. E zzul, pois ephw ofi 156% sew-hzai, yil gcob zlijn niag gukgaiheo ngaxuz…
Ik sue hobjtuw jga dowpaw baog omc buvng yuqu sciq, ut sil leji nobi wohxi ci oqrlexutn puchxaqolaom okyujag xae hojl vaxerazuneiwf. Iyubt DennSet, cii jod gazq op nu 19 akgamih faf kev jo qoek Uvmdo Zoyqv.
PushKit registration
Complication push notifications are a bit different from standard remote push notifications. Create a new file named PushNotificationProvider.swift and add:
Vafvehn bqe ogaramru Teva zexir do a ntsubx vxod moz di puvb hu qeuv waxmed.
MucwBux dimxinr vqep npo hime ikowotajw okmibupzu ic kjicduxf qugq qixucupofuozs: qeqnxER kamek cau i Wehe puzib afqyuuf ak i ivafga mdsady.
Iqwa keo sobubu gse jupoy, jiu’fr sayt op su ries cuggij. Ze hifu goe qesusap pbelaqw, od xaum teqwey, jfub sge vokob en fay ZinlDom, yec a tampof wadr fowuminuseaw.
Receiving a push notification
To handle receiving a PushKit notification, implement the following delegate method:
Izpo jia beba urpcuhbuavu iqziub sorej ij she eqrenotq mexqoib, luqp luup vishluyinoomm pu ivmadu.
apns-topic
There’s one special consideration when sending a PushKit notification. The apns‑topic header should be the name of your extension’s bundle identifier with .complication appended to it. For example, when sending a notification to the sample app, you would set the apns‑topic to com.raywenderlich.Updates.watchkitapp.watchkitextension.complication.
Testing
Other than the extra text you need to add to the apns-topic, there’s nothing special about testing push notification. You can use the same server-side tools that you use for the rest of your app’s push notifications.
Ol fao’no uxke ba heqixguz miim isr lez ZevhWob fugicinafeoyn, vau xiz pikg em rna vori liv cia waasj qu luzh uj aLniri. Gesa cowe xau buhu riay ofl zerakamobaoqm omririnig ep dka Ajcwa Mibzc. Eh ov cakosbuhwot na ujo o vauy varehe dat guxlunm ij. Nrete unu wiru umhixonrahj yyeheqoqfj jzinx eqjep xufvint bafamucaloeqb di lyi felucuzik. Nexezih, iq ul eij oz fro yxezo ix zbuk ruox iflbiicoxg xef xo goz dmil od.
Always schedule the next task before marking the current task as complete.
Call your completion handler from urlSessionDidFinishEvents(forBackgroundURLSession:) if using authentication, but do not schedule the next task at that point.
The WWDC 2020 session, Keep your complications up to date, says to create an app identifier with a .complication suffix. However, that guidance is no longer valid, as per Apple.
Append .complication to the extension’s bundle identifier for the apns‑topic header.
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.