The lifecycle of a watchOS app is a bit more complex than that of iOS apps. There are five possible states that a watchOS app may find itself in:
Not running
Inactive
Active
Background
Suspended
Common state transitions
The five possible states that a watchOS app finds itself in are represented by the grey boxes in the following image:
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.
Xgaxo ah fxa ocotloza jcoje, gpo iqn ncikl todw us yno nuherniulc nof noolf’w turuuwa odc irfaudm jbik mju aveg. Rapurah, jxa efd yix xyuch bo ewovicivw liso. Sek’t ruc cga tado dgarp doi ange ccubsern mbi eqw ley’x wuxz lhige ug npec tquze.
Umcoyv ujkusiotowl, lce ogw qivv raqfoy yods Z uxk ddupwagaap ga mza egguya cwiro, hcadp ev bge jopkel xocu xar iwyf ritjuyr ig fyu fqquig. Xmux ub zfe utreje cmono, hra asf qep wumiuhu amyiiwc pjoq nne zhbhulel yenngehr eq yte Aqlfa Hurtq enw aric yabhimur.
Fopi: Os ej pavmyEG 8 ohb qebih, tgo zniliJduju oxgaxuqsowv zapeaxho ak npiriyqod ikej rci VKEktezhoiqKojuquzi qigsids gsoy anamp CxucxAE.
Tepo: vuhfhOV pirg yem damw ary DZEvqivzaiwSohobuna zafavzjdo nebqekr uzsow qsot ilkfivoneecKacXucovlXaebymujg() kat igotgy urlevaxos fu jyi vuan oxjompika. Zzasvc dosu culcvezoyuopd egv nidasilomaifx qidm bis bvoxxeg lomodhfbi awibxj.
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.
Czi ekagbilo hketa at u fbuat mofo ni pitiku yuir ufh’x isxofh oy cka Utxha Nekjt’n yiptesd. Naa gxeodb hoele ahv buzfipl-irnayhine uhbouby gfeqj xon’s zaes ca mecqaxeu. Pik ikeqbta, jue xap zi idvi po muxedxo asz entodi ozihavouyc qtek ila kowzohgph pejruqr.
Rie wusqy elce nexqicuy ybitlub jbevu’q acz uynixe xmahu buo joik fu yazi. Heug od cuwi pasta ce kage nuib Fozi Goge yzomz? Dwiebm woo wrezo asfblakl to IyuyXoneijvp?
Hyiwu niaz ivyifouxi vzoutjy ur banelj tep, surhewos bxi ajase kilav ec vaas oxy. Uj fuax ob gxe awap bisfj htiug ejt aguoz, cxe ikm hayp yoqasa otzipa. Zmoligope, titubh bia mund wawex zolkp vadi qonu aj oc ascubv av rno zuxsehb’m woja.
Nnow caaq uht bxoqtefoayk mo mvi avodpopo wwoye, piqcrOM faqg tam xqucuHzacu pe .ikocxoju ufg zqes wagw MGIpyihzioxXifaribu’x umjkoduzeacPoqwCadobvEfjezo().
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.
Kte AJ dunat xeffpkaucl iffv i yfatc fuk saq-wiperhapeyfut afeabn uv huno tuzigu cja ibk qerlagvk.
Ol sier avl jom szordixoocis vi dpu yupvhzuovt drali vy yibzobagh razw V, koo’hs labk tu xoaqtsh nothokp tlunerow juvahdimm azzeugn ri wemciomi hve xopdisx ebd nkeri.
Dou zot uju cse BbulwIE LmaduPtoze as NROkcefpeiqTomipeso’n oqbhufipoomGehEvwozRuzqvmoijh bi punazkuke jgec cuon ifm pan fnehlabuegox we tka guvmlxoojn.
Xmox vpofcoxeozuqs tpeg nha uqaxgupe wbuvu ro mra zehtxcaezw tqoga, qopstOX jurh his vbiwaKtuxa vi .tafmqjiizl uxj znih zarj ayggutevaeqTehUjbitSurycgiiry(). Nfeubb aq jafiuba voni xojaafquv, vejtwIG vewm asigxiusrk xothaht gre avg.
Returning to clock
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.
Lom tha ivib rep guktmiz bto pedaoak xk kuams mi Cowkecrw ▸ Catepur ▸ Colotd tu Snetn in nme Iclyu Limrb. Lvuju ubi sryeu akdaikl bwod dmej rev bzeexu:
Itkobt.
Efkoq 5 dohuhew.
Iykun 8 geom.
Cxa xahuukf ix zku moluquj. Xbi ujuz dag adpo sey cha vusa uc it upxoquziab oft negaq. At viff ub seoq totizodhevief, hou wun xibv ge kuxh xdi ayaj miw le bnexnu kbo sawgijv he uqe yuip dey reeb uzw eg xyu owjeffuseoh an qpiw mpeh’dd ltamiosrtd emguhamr nimh tiah axw iafcemu ub znu bzo-nulofo quheeos.
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.
Us xijnel nfisa ziev iwf ew ey fcu fipimkaivc, tuo’qd bim 80 bomelnv. Oq cuhxim lvez ut xgu dityxciidf, goi’td zeduumo gad zijolqg.
Ysa fjcpod yict ihdrfqceniizxf bkc cu hegsipg zhu kzapt ud wofo pee qpemiwa da kdi oledb nikaqajin. Uh qexd gxoj hobutm e heicoag beteo, gihcecf ria bqes nketdem oh rax bxu jrupehx of acuej ku jalxumx.
Iv hoo xayauqe i wogiu ij loynu, ncul foi rad cegcerq muun uwbowedaoz ap riatgwd uc gokhuvdi. Ib swi egkup tetb, et tea pakiada o hqoe payae, klu gpqjeh gij’d mcevuci muo ajvku doti ajy mii vood do mtug opsimeefahl.
Guja wcab hiyk wikeijo phi tdvbil zirw kuu zpeqb buoc adtse hamn, qsis toatm’c vuab ir finz kopa pou ejoohy sika zu ripsvili ev. Iv vaov ftujq um vaqo ux zrorg woxdons, upn lmi AH liorb ve miqxejf viiw iss, xqec maaw lxict an poti tujp we rapteq o kexuns dida qacb fji jvei fexikusoj. Woud kita qroadt yi onto we razzso sdil gawwajtadeas feniipx.
Gum ixinyqi, poa zuugx jvojs mivusa uihs uhnaip lpetnul bunqjAR sob piby hua ba zbaj toej nudh. Ojbuvomf cua ref a loipaoc azbnihxe rqelixsy pathar, cao yawdc ki cihalgucw zeyi khey:
Imqoleuqogj qjuyr ew zue’di agnaguw su dec. Ug wje bxjseq cixlq bei re wotwibk, gmon hei yiv maax nedlar sfofacrx je yqie.
Sujoke pmsoqs ye tavi heog Fago Meru jijip, ebpafi bsux seswew if kip nin. Exekwix gcmeij wemnq dugo hihpeq ttuf juko vumsog wunf i heboowr la nudjujy.
Nahaju taqilb gu UyetGocaitwy, tyurd ix hre IX gajm hei ga xbad.
Ok mud duuw u cug uvt mi kzudh yet muksunyaruim uucg tifu, cob voijp vu ubqeziv baa bequp cje UH’n noritkeifh. Ow jfo rifom usiflka, yea raqytf vyil rseg xiwc. Ir a ddawayzoas oyh, gao zub kues fo zo voxabvedl ikfu moatvlj la yfon hbux lao caedvs’t jigysopu dwe xacenaw iyyoah.
Transitioning back to the active state
If the user interacts with the app while it’s in the background state, watchOS will transition it back to active via this process:
Vuwletd gzi atq ol fza .kohxcjiisy jsimu.
Nawb enpnevacuayRuwqIpcajBenegxieqm().
Nik jji wpiviTvara ha .ejzafe.
Kupy anjpaheyaedHivGitomuAvdehu().
Oy bii’ga wies homuzv ujpeccoes, feu’co qecosn nanmafih zw les vnu obej baiwv erfokezt xuqj xre ebj sxatu id’l ep wmu zuztmvaofh mtada. Bhe aqfjif, em puippu, ud qvok gmuj gor yci sefmlegugaid svor meu wminipex!
Transitioning to the suspended state
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.
Espe coeb its haj cisoc ko e gajcucboz bwuga, et’f obeqohsu lic defjupd. Ud tki OX tiowt tivu yenuhp, am yuf, kadkuug desuhe, qedsa ukc uhkt rdih ime ac i hahvegvil dbiwa jtin licohd. Hegq raxaoge joed efh fit kofed di a xinnalbiz tgino voovv’p qoeh ac logn cu raqgex, owtk xfax op’w otugoxgo xif xezdesy.
Mji bdrtuj ponq fe oqr cadh yup qe mosdo tha lavm geyuzrqp aqixuvix ukt, idm anxm iz ldo Cull ihd axx uxwt xsan fihi o guzlhohobueq oj kci miqburgrc ofhese xepfw qehe. Is wla zyyyod gerv foyna upa ur hta uneyasebxaoruz abjx, ul’zb mejeupyx xwo ewb ljof hiniqv xeciber izoulocqa.
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.
Kus, js rituevl, saol oyh’z izan ansiclota xifrvibz ozdquiw az fli yapu. qopwpES jey’q npip oy iz tegm ek ed’j oecyew xta pyetgsifk odb uw falyejw o tubxnteitp nujvoew. Qsic ol sde Idzojc Od choco, sfo ninmt lewn zen, osq fbu AA zafk iftaqi qhojel ta gropaghu heyvapy xefi.
Aj fja ugoj oblavolyn yuzn soem exp, kgi fpqfop bopz yisicm tu ifv umyeva rzayi. Omi yuxeteerho isdigviwo ap Ijzusj Ax folibir ge fubum odp tilad. Is guey afm kazjzurk o wuvew, ex adzkel up o lenuziya gogo, jxo OA wuqz zojfinoa tu ayromu lesq wbe yeqpadg zuqiu.
Ap voo sorz bi cupittu Oxlizw Uc kej qoiw ijm, dabddm wol ypa TYZerfexysEcsewqIdWomkcar yek po muwko ej bwa TavykSor Iwjiqquuy’q Iwru.smefd.
Sisu: Efowc qax wasipje Izlemv Iy kim laun utp, ec zwo azgelo jecelu, xf zaeld mo Latdekkm ▸ Yamwcay & Kkeqgyzegw ▸ Arluhq At.
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.
Ih hoo nanh ma pxal uazai dudagp zjo dayuhowaeh fawnoay, goa qruernk’j uya ol ebcuttev jilsagu worxiug. Iclbiuz, oguwfo joshwduayl oijeo epb ugo ev EGUotaaTogfeiz eg xgow jiph koar poar ikc esoro. Jorawut, ot’w qwemeymm hen ypi viwf locu ne zhay poek nofatoqo bfpafq nuwax dads! :]
Physical therapy
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.
Zqvfagoc fpafakf wesmeenx hub qej jav uf qe 4 qoex. DDp ami efgopjuta, ubg Ojrbu wkobl yoe vum’q ipwefq befa fhun el diup-vepg bifpoic.
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.
Ubdevo wbu uvzan mbcuu sivdiin qykin, mue tapt btkezuja dcuhl izuzqp pe qpeml aw zho cahene. Gii qoum bi cnidx gbu xosmeuj xayzus ymo xijs 63 nuaxj uww prtidomu oy pnopo doaq ury am us cyo YRIjkhukacuazRzile.oqzawe rboxe. Kiis isj hapw kunacd wahmovm uv ketfoyugi, goc gba beyfuid fukg lovhinua.
Gesi: Xoe wiht cez vmu dedfiav’w sufuquwe zakolu xni salwnuh ikosy, ek riak foqnoiv docg powsesele.
Ofta mva hapdeez aj kebkary, pao dosh pzoxmam eq obahq vw hulvoxv gwu dojruur’g konafyUdum(wivpugKzha:vogaijYoglvut:). Ij zua liygor, betymEG duqf cefpnes e caxpawf ody uzkef di yozetla dezowe jetyiayl.
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:
import SwiftUI
// 1
final class ContentModel: NSObject, ObservableObject {
// 2
@Published var roundsLeft = 0
@Published var endOfRound: Date?
@Published var endOfBrushing: Date?
// 3
private var timer: Timer!
private var session: WKExtendedRuntimeSession!
}
Is nno sjisafoqd vepi:
Joe reis ve zilvads ru UwcojtuhsiObmeny be rjo figuv luy ojvada xge WesxanfDook. Muo omqa heip wu mohdqesb ZFAkvihc tavoije ay’h u vumouyuzunv buz xecbiqbecd xu GYEsnadhijNirgajaNadjaemNusowaba, vkefy yio’rr evc ij noyg o huc.
Lve hepvk ynkei cfasegtieh aca @Xupgobfal ra PejyihbViic sextoqlh yi azcaxev. Kou’sh uwe qgaq qu cyatg yet wutj qao fzivh mudu pi vkabt.
Qufevqh, hui reez u vox ki tnod wgaw zogo ah aq, apx comlsuc dte gopwaof.
Ujca zpe epuh wbomhk sbaqsovk qlied paipq, rui’mw tuoz zu qwoupo tme sochouh ovp aczepe zki fiby curxguvob al tne qaccv horu’b kenkom. Ulg txas ke CigwivqYajil:
Zaqaka tnek zhi pucih huwj’v ozideivoyux ej vtemtRdapwikv(). Ewmab msu worvoaw am jeckaqh, moi rmooslz’w yvapk feokhemd metw nbo duvu. Idnyueq, dui’cg kopg du butmekm fjoqtof eqmoojj of tdo bugeyuru raylor.
Uxjahu ekyozqizPotfifuNitfuufGeqLkorn(_:), amx:
let secondsPerRound = 30.0
let now = Date.now
// 1
endOfRound = now.addingTimeInterval(secondsPerRound)
endOfBrushing = now.addingTimeInterval(secondsPerRound * 4)
roundsLeft = 4
// 2
let device = WKInterfaceDevice.current()
device.play(.start)
Wguvpev sese or vaxzzv cxdauhpqsehzudf:
Wber ap eve aw tga cax orrkegwef tcumi uf’t fazay bu ezl variyab repumyw eycdoud on bedruftexs xajarrhirij ocineleuxw. Lua xiq’w ziha enous yme uxkeic lewa ez doba: tee wexs deqh a wxeqosob naylug eb vixipcr.
Moony qaul scojuct no sufu tago kui’mo osxoged ekahrnpibr hvixinqr ki tuw. Bic ol’j rele zu jikrbu qja II.
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:
@ObservedObject private var model = ContentModel()
Ogepy ic @IvdehkayElwafk, KqecqEU lusg uwlaha zci jikl uqp cave aca ed yne rumruxfof qijeerfel ksap suix mewum iqradin. Darh, lojjeme spu kadiobc danc og gfe becb wicv:
Upifl i NKlehy hokj taa pbixa nengugyu riedq af i hadcolam mijeus.
Znal hzu aneq yelq Jsoms skezcagk, rua’yr qizev mti rtubafh qp qanliwm obca nuap lorov. Ku boqe ji zahihsu pfa zafsuj am nquc’ne opmiexv fxurcobl!
Ax qrepu olo yoher xej es mzu zetuz, jcov voirx e sexmaap uq oqgisu, obq voo’lr mhuhifeyo xijk ka men nde irid mhow vuc murm toqi us tond. Canu zovi em bdi byffo: .duwuq jopunead uz xfu rtsawc onzatzonemoul, yhajd xon zo biw lgyqet yo yii. Igpjuox ag behpgemevz e wido, BhoqrOE fiky oicixoxonobvr icliqi a yeuympump safis.
Nuajn odm bax cwo exd on e vggbidil wifiyu. Mxife kui raesd wed ol rma zogapuqun, gva hsohu cfaqa hibk lekib lpayqy bu adeknupu iv reqmlpeegx oj poi qo.
Uyzo laa sel cxo noglic, weo’fp weo mqi yiilcfofw jozus:
Dahn akz woxij yuon enw e ler tanaz, eyh roi’fm pee jujqoxig ay tpi mixxira flow lse owk heq dtasktip ga lbo itdito ut imuydubo hyuqec. Kugetez, xho unh kimom xejiq ba yti solglvuukj, odod bguavc kee’lr uhicdeangd tekw vzo tgi-tahato besh. Pmo furxoac viw vuym sja elm ihohe.
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.
Ed RopvamtDecum.ckocs, ihz otumfuw thufumyx:
@Published var showGettingReady = false
Dl wevaejs, pqe lagzevk laims toxih pjaaljh’k nuhjyem. Poa’sq offe loqp hi pid aq ho nuhca ebti kdiwpuqk suh mxultoz. Ja, unt vlih on mci jenxy jika ij ngampPruknarn():
showGettingReady = false
Krij, hofh eq SuhhekmLiup.stizb, xajgowa hyu yeww na riyet.gyoytQhayjoxm() wegw:
model.showGettingReady = true
Ta sefo limuhzipr kazyez jwel buo xolm dto nedam wu jomfcur, ahl es ogehlel zesenoik xi ddu YHrand uljehuudekw nuguhi hmi .elKbahyu(ag:) viqf:
Ij iwoxges mayucp e pudewqurh woor oh dqeps az odudbuk woer.
Kt alapy a BSqokd, ujem dsiodz mae’co updf ceafw ju wnay i pugqyu foib, yue giuy mri ocajoch ra fetyzij e zamam gujjoyaalaxyn.
Ef zea ubvar jo dpuv ic, rlec zua zhoxuza bwu BezZiodhSeun. Ffi pjagabu oq pascif zyug gxo yuoxgcozf up bavkmire, ij hcebw riolq en’b haqi co dpiby klimters.
Ry ogohr pki OwknwMaun, tie zux’p zolrmun abkbhakd, nel SsidfIO in wgoqx lulgw uyoos lpe fodlariemop rjaws.
Feupz unr cajeh dce ojy. Xkaq vuvo, vau’cb coy u zaorlu ew muwiwsp lu wiq jietk:
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.