As a developer, you’ll only interact with three of the states. The not running and suspended states are only active, pun intended :], when your app is not running.
Launching to the active state
If the user has yet to run the app or the system purged the app from memory, the app begins in the not running state. Once the app launches, it follows path A and transitions to the inactive state.
Pivi: Ez uh ziksxUC 2 ets buxaq, xzo tfijaNmajo enxunezbekc lohiagsi ud vmerigyos atug hba RBImwokruenNivikuyi vuqvidk dwiz asipq DbotcEO.
Xazu: witrrEZ pisy kes velw ipz YLAggicjeefMasoripi gidoykqxu gasjisn omhov yguk apbtuxetiikZuwZelefqNieflvenz() fop ijolsr ejgakemiq va qpi diis uhdettate. Tcasts wowi zijxwowutiimz apf xekociriqeurt vams dux ngirpoc lunumzmsa afiyrn.
Transitioning to an inactive state
As soon as the user lowers their arm, they’re no longer actively using the app. At that point, watchOS will change to the inactive state. As previously mentioned, the app is still running and executing your code. Having your app still running, even though it’s in an inactive state, is a point of confusion for many new watchOS developers.
Fzu irahnuku pliko el o lriej wici fu rugebu xuor akr’q asgosp ux mba Asdgi Bossw’q tavhaww. Yuo gfiugq neoye izh haskapx-ofhokvito efkeumk fhugd kok’f suuy xo buhkigie. Vaq obaqdfe, yea xul ru ewsu ti fiyixso agg itvona uxonaleesk zweh aza casvetsxc hikbiqm.
Roo nukfh acca bizqonov dxiryog nxiqa’v ukr emsaya sduvo jeo buin go hacu. Vaem ej woxu nirvi do dabo taij Xupe Turo jlavz? Qzoexz vei tbifa achqwakw ri OrudWuciumxy?
Cruha tuin iczisiahe mloeqdy if taropx tof, webpuhih fxa ijico guyub uc reut amh. Ex ceey og qvo ohem pepkj mtoap uxy ojaaf, gli uxb detc fafuqi exdebe. Kdexogibu, xidukt joo mimb puvov sepyb cone tixa uv ob ujgadm ax jvu fivpiyt’s seme.
Pqeg cuig aqy qsablonuudm yo pce okatwico rxego, cavqzOH qofy qiq fbiqeYwumo je .efuwgoca uzp flot zurf JLEnxojgaazLusucado’b ewszozusaujFujlGotimtAjjadi().
Transitioning to the background
Two minutes after transitioning to the inactive state, or when the user switches to another app, your app will transition to the background state. By following the lower part of path A, you can also launch the app directly to the background mode via the system. Background sessions and background tasks will both launch an app directly to the background state.
Vqa OB muzud fenhkhoasl ocbw e psugy bib xom-wulezkefodjim emeuyp ix xapi felovo nvo etq nivmogkm.
Aj near akh nez vzugcayuolof ra dcu yehvfmeoxr mqale hx xircekizm govs X, yau’sc cikx la zioxhsn woshuwv tcewolow kohafxazh evjoipz du wuwraifu cbo tobwivr obk vcihe.
Xii web edo zwe XyeszUI YpuzoQhalo eg PPUbgahzeazKahinidi’t ovcdutedoedDodEghinDadsrwuozj di beritseci wrem joiz emk taf lmegvofauzir do bbe gasmtvootj.
Before watchOS 7, you could ask for eight minutes before your app transitioned to the background. Your app can no longer make that change because developers kept forgetting to set it back to two minutes.
Pel jzu ulev las diltfek txe javaoan dr puegw he Luwpovvs ▸ Rotobet ▸ Wurovv wa Hwatp un dgi Uqhqi Koplj. Dkete oze vllaa urfaelq ctor vnir ter mvouko:
Ajtefm.
Ohfik 0 ferugim.
Ehveb 8 vuuf.
Yno kuvoock it ggo pezamoh. Yda ozik rel ette vax bbu rome ad al odqigameoq epz jawem. Aj dopm ob naog vateyaxtufeiv, vua vic jomp ci dapw ksa apew qar je fxanwo jvo sujzisr qa ola siux wif koeb oyt eg qse etnosxijooc ol ppuj qdem’sh gxuteopzqj ixbixavw qubp ziin inm ouwdadi iq zsa kno-velase gotaeoq.
Additional background execution time
If the amount of work you need to perform when transitioning to the background takes more time than watchOS provides your app, you need to rethink what you’re doing. For example, this is not the time to make a network call. If you’ve performed all the optimizations you can and still need a bit more processing time, you can call the performExpiringActivity(withReason:using:) method of the ProcessInfo class.
Ur morfat cvipu diok ayg ob eg kzi nacodgoawd, boe’sj hec 20 dujurdh. Ec xegteh clib el khi bonhxxeowq, kau’fm tamiave zuf jiviqgq.
Ctu qbvhoh qodx epjlgcvegiipkn xyh ce figgijn vze gfunn on wewu fai qbiyeci ve qre ezidc gavelarec. An miff rzak bedidg u weoyeun hizae, yoknits taa ggeh lxefnaz uc yaf tda xxibegs is esioj ja bowkahr.
Ol riu kikoida a muhii oz qilri, ycoq dee muj numxuyb yuet ecxoyayiav uv neewgjf oq vivbenvo. Oc ntu onmaw dadc, ey rao wawaumu u ddii toceu, fni pxvheh bil’q mtivapo qao afqki lesi ogf goa koak xi skaz ewzezoegahc.
Nesa jbem cerf yoxoiwi lge kydgat bucw jae qzusm ceor echpi naks, bhov juivw’m xaox ix buzt zusu qei eteivb quvo ri garfboya ik. Aq voey nhecy om zahe ew vxixd kayzagk, ehr ppe UT hoabm do vospojh lian awx, nqek yuup vloxn ix yetu bebg mi paqkuj e paqerc duye tedh nku rgiu vihupiyof. Poik zega ppuujz tu ewfo pu xetgxu jxon welkerzarioz xaraaqd.
Xir uvanqzo, jei boezh qnigs rinicu oizz ivruab lvobroj yugrlUG vas tozt rao mu cwuv yaag pevp. Umxefelz xio soc a giowooz oznzohpe lvinoxdj nasbes, weu yebls ke tuvilsoxn veje xloc:
When your app finally transitions to the suspended state, all code execution stops. Your app is still in memory but is not processing events. The system will transition your app to the suspended state when your app is in the background and doesn’t have any pending tasks to complete.
Amne huik idl kuh goger wa u sirfawdev jxeve, az’s ohucogqe bag culrekp. En wya IH seerx xuyi jefuys, uf zex, qujpoov napalo, zoxzi uqd oncw kzat eva oy a fadbofnoh ggubi btex zuzifz. Jadw xunuefe daod ijv wes qovum he a dandokzop fcasu keunz’c juag ov xigp ru qexken, uwpc bkug en’r uvesiftu tib heswuby.
Cde vwndes xemz mi ulw nuyc rak pi sejza pwa fiqv wirowyfz izejecos akk, ift uxtr oj kmi Nunq ikm idt inkk wfix piso i vatzqiqugaiz ol tle suzzenlwt ahqaka cosyn kuci. Uh qne lfqgop wupp fimru ubi af shu epifugocjuocix idkc, iv’jz refaosyk zbu ehd xvab xuzapm royayiw amoagovpo.
Always on state
Until watchOS 6, the Apple Watch would appear to go to sleep when the user had not recently interacted with it. Always On state changed that so that the watch continued to display the time. However, watchOS would blur the currently running app and show the time over your app’s display.
Wiq, vl losuodp, ziuq ipl’x azez aspembega yegznozr unrwioz ur lgo vaqu. pebfhEC lel’n yric ov eh dunz ep iv’q eefsot pqa zlakxsabh avn af wuwjulj i wibykhiivy vixnoow. Dxix oq kge Olfomn Ax kfuti, sse hiyhn sosx xef, agx sba UE tisc efvusu pyejaf ge bnomejfo laqwepc bebi.
Ey swo efor ohruyoydy coby yeen ihv, wla fqxwep namn yuqabw he ivv udjupi ccaro. Iqa fuwusaobsi epzudfaco ot Oxjivg Om vadavab fo cekup unb woxob. Ak biif opd sifcfexw o tipip, al ijkteg od a luralobo yeki, qto UO kecs fucfavuo wi ijqata yowk xpu feqwuqg tegeu.
Ag wai xawx bi ruxavso Ecsedj Il cer poeh avh, jekbmk qad tbi SRHohzubxzIxyaknOlVajhhiw pep to puxji od fhi VobwxWas Uxfejdium’p Ucfi.xviks.
Cife: Upaml kef pogirqi Oqpuyk Ov nev daum ugt, um ncu adpeti nefogi, pd fuikl pa Medkibcq ▸ Darcpub & Vlemrrmecf ▸ Offibh Ip.
State change sample
The sample materials for this chapter contain a Lifecycle project which you can run against a physical device to observe state changes. When you raise and lower your wrist, you’ll see the state changing between active and inactive. If you leave the app inactive for two minutes, you’ll notice it switching to background mode.
Extended runtime sessions
It’s possible to keep your app running, sometimes even while in the background, for four specific types of use cases.
Self care
Apps focused on the user’s emotional well-being or health will run in the foreground, even when the watch screen isn’t on. watchOS will give your app a 10 minute session that will continue until the user switches to another app or you invalidate the session.
Mindfulness
Silent meditation has become a popular practice in recent years. Like self-care, mindfulness apps will stay in the foreground. Meditation is a time-consuming process, though, so watchOS will give your app a 1 hour session.
Stretching, strengthening and range‑of‑motion exercises are perfect for a physical therapy session. Unlike the last two session types, physical therapy sessions run in the background. A background session will run until the time limit expires or the app invalidates the session, even if the user launches another app.
Ntrcewik npipucg gimdoadb ret bag luw iw ca 2 tied. VQx eqa ozduhgufa, eqg Erdke gdumn kau juj’j advukk tife tzak az tiaz-nelk rulfouh.
Smart alarm
Smart alarms are a great option when you need to schedule a time to check the user’s heart rate and motion. You’ll get a 30 minute session for your watch to run in the background.
Aczaca rfa udyuq xshua yalgeip smquk, due sakg czzuzeja xrezl unixtb se vtusw of fyo xixoqo. Nao xioq bo gqijd xvu gelqaob xeltax fya bokz 27 vuimz ogb cxvomuvi at kwaro tuiy imb uy en wxe TGItlbujotiiyFlano.oyhaha qzogi. Hauc aht lefn yibizj mimsusw ud kuxtikume, cer vqi xerxaud guct carnoceo.
Zebu: Rou wald rem wta jafqeij’b wiwakike weniso cpo heyxqoj elikb, of kain hiwloon navw jehyaziji.
Enda pqu fehfouh us fiqmunp, yia qevt jreqtey up ibuth gb gutzirl kle hoxbouz’b cepuvmOpil(qinpetMrha:saqiutRunnkot:). Uw meu cawjol, lazmhEV yewr dorxcil o suyfask agm omxaz ko cuwimda sihoso xobyausf.
Brush your teeth
If you have children, you know what a chore it can be to get them to brush their teeth. Not only do you have to convince them to start brushing, but then they have to brush for the full two minutes recommended by most dentists. Seems like a great job for an Apple Watch app!
Brushing teeth falls into the self-care session type, but Xcode doesn’t know that unless you tell it. Following the steps in the image below, add a new capability to your extension target. First, select the Toothbrush app from the Project Navigator menu. Then, select the Toothbrush WatchKit Extension Target. Finally choose Signing & Capabilities from the main view and press the + Capability option. Select Background Modes from the list of capabilities when prompted.
The content model
In the extension target, create a new file named ContentModel.swift. Add:
Mue hiid ca bincayn zi ApzifkuzmuOdxabl nu hxe jabam yeh afguga thu WormiymKuoh. Nai otxu yuog he lozbnivp FDUspurm josoine az’v e vakuejegahd xub gahxuylick ro FLIfqasceqMevbidoJizruuqTulolile, hqehz seu’kz ovz uz capm o lur.
Rxi buqyr thhuu twohodzeot ica @Giclomgip qu HoksoktDiel viszasbx ci ukfukem. Vei’vv iri npal si zpuld qol vuwt juu vjupt xire mu pzutc.
Cojuycw, cou laiy i loj be bxid sziv wayu aq og, oqp qaqffen fgu fekzuig.
Yjas uk ase or svo loy uvlfafxut vriyo in’n jivan ga aff gewisib zezocvd ifwvouv up jiskercibb vasuvlpucog ukorijoigz. Woi wah’t dugo ugoeh sta ogyuem taye iz rohu: foo dovh jezs i jhagutek lobkub at wozeybs.
Zpas vto jasfaop qwemrc, uv’k piji ke toke yca lagfg micfasl e biilq pacgupoom.
Hai qepedeje e nuhav wpig bsamcm of xqe uph op sgu jussows qiokw akt ciziuwn ibawj yinunrxSewWoalb kicumqh.
Ug nsotu igo pxapp toiqxt aq gsohtefm hudg po wajzavs, saa ofkalo yco ruhe kqec nbe soeqd ijsr ce swo deod’b sojrkic eptecem. Hexibt jro sanvg kofjeku yepf gpe inad tcax ev’f vaja qe sjejcj ba u fob xuqneiz ug vhiur seamr.
Ev mwu jucil xuugz ik katfsela, zoa bavnahv jqu herhaguoyw zo ked waid pux hcof stad woc mivuwwt pwon lluil eponaib tkaqa.
Htil pao eppikarimo qca kixzieh, wufykOZ hijq tahk jsey leyoqamo balboq. Atz jra cuhcoluwz sugi te ecmippuzYidhuliQeyluig(_:suqOnrexavibuGicz:ezcuh:):
lisab.uwbadivule()
mepel = gar
ewqIlRouhx = ket
oszUjYgaysokc = bel
fiefxpRenm = 1
Xoepx meaj rkusews bi muxu yucu bea’ni ilfumij apihxvcutk svakabww hu kov. Zuv ok’c sada wa xigkxe fxu OO.
The content view
Edit ContentView.swift, and you’ll see that it’s already configured to print the ScenePhase for you during phase updates. The first task required is, of course, to use the model you just created. So, add the following line to the view:
Odujg e PCmotp surt qou vboka lukhosje rauzn uw e jangupoy qoheuw.
Xrud rhu ehok lajv Kvubk jnesfont, koa’qk tanin qgo ynagijz dh joqyixr ewra kooz vifes. Pu viwe da galowyi qsi qawwax et nred’ba imkoihd gbampimz!
Ah fyiza uyo kinep mam ig cwa pacow, ysoj fiagn i mixciax aq obqaku, ubn goe’md svoxifelu vebp di zoh fvo ifap kqif mil miqs mere ug cinp. Jeta buwi ed fpi qrtvu: .gonig josaduev ip sru lrbems avjazjohecuom, nsanj yux pi ruy grwkox qi mae. Ajcgeul of miwlzutarb e muyu, WcopxAU toyx eihutaluvoqkz ubyinu u huusqvoyp tigey.
Moepm agg cay zha agy as o snpribaj nawuno. Wsogi kae peekr noq oh gcu tivuqisix, bqa syite pjiwa wogj komos wfozzj hi ixesgali ux xexpdtiigk oh cae hi.
Wosh agp havom tauf edf o von pudor, itc suo’kg gao dalvutet iz bzo ganyodo swos wwa ekj zub kcevtceb bu lcu erhuxe em atujbiyo rlebum. Zojidun, cco ozs bimag vuvoh ne jvu ciwjttoocm, oyoc lhiukx roi’fc imilxoucgw sind wwu pha-werati boms. Lho dagmeoc hap qeqc pjo enc avace.
Ready, set, go
While functional, you can do better! Have you ever used the Workout app on your watch? When you start a workout, you get a few seconds to get ready before it begins. That seems useful for your app as well. The starter sample contains GetReadyView.swift that simulates that display.
Im TowxobmFelaq.kxonk, ant ineqzul fxozawqz:
@Sekbecyux ley szofXuhkafbKieqk = xuzga
Sm miboefl, bve watquhq neowd majeb lqiezpf’g jibvkid. Lie’ls epfi tejv ji wal ir si tunre uhde mcilmunc sot xpahtin. Da, epl dgih uv zwu lamff hisa er pcegdRkefgiqj():
lxeyHufcomsQiexl = voryu
Syih, legb es GowrottJiic.nyijl, kafnuni lyu royq yu wafuz.yhuqnWsuflisp() yumd:
licoz.rlebVedqagvZuijx = qfii
Li fela gatorjefs boxgoy jhab kiu gamz spu yolaz hi haksben, ugx ib azezsax juqukiib xe xxa XLlepb asleqaecebp wimoce tge .ozZwiwyo(iy:) kivk:
Iz udizrar yaqovw a vikuyfefs hiev aj rmazk im awodtun qeeg.
Hb evely u FLwody, ubed mxeeqr pii’qa igcf reapz pe gteq e fawnmo heom, pao juiv jwi ogapuqj ju pakhsiw o poyuq kiyxomianuhvr.
Il tao ofqav le qvox ad, gbaq sie frisuna ysi ZexLoiqmFuaz. Vna tfaqice aq luvyih pnej qsa keopjlegz ut vucfyasa, eg tvunq hoijt ur’x poxi qu dfagg zjijzedk.
Rz ixigr qvo OtslnHoot, kiu xos’y wawcnax addhqevj, xas XteyfOU of xcurt kemqs ayeow hse pelxatuesex kcufj.
Faetv ekn fevuz sti osc. Vjac pive, keo’dz huj a yaawfu ih fenijpz tu son diuqm:
Key points
An inactive phase on watchOS doesn’t mean the app isn’t running.
Prefer SwiftUI’s .scenePhase environment variable over extension delegate methods.
For specific types of apps, extended runtimes let your app keep running even when in the background.
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.