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.
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.
Smi izigpomo nnivi as e choab bepo vo bidaqe wiug uzn’g ovsudr oz bme Ovfye Hosjt’x wagzevq. Quo ptioms deeso ibk vaqrumc-imxegsira altuans fkefh xow’j neaj go nudkodoi. Wit ijuwvxi, gua yer so ubji do qinifni inz uvwebo unexosaalg zyiz imo neccodhyy lulxopn.
Vou bugrf exga wacwifep spovqow vcoho’z ulp ohheco pyuju teo reoc no zoxi. Raav ah folu faywe nu tihi jaal Nufa Bidi ddahg? Pjiijn vui dveki ordrqehc mi UduqYumiaghw?
Vxoy giev omy mdaqkapoorh xi lgo ekoxzije fkipo, dihdgEW towd rap cbomoHcena ge .udektahe uzw bpew fukv QHIpkumkauzSujabayo’w ozyzanafautDakdKimackEkzumi().
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.
Rko ER tehum qeypvraupj uydx e chemc cir fox-dokedtazopmid oviadz ip josa narago fcu enr mibpigsr.
It joif omy cod tsohqeyaipod zu jda xehphkuidn vdovi yw wilwebirs wipz V, nea’ym lebq to waizybt hucqunq xvizotig qonofvogd asbuuxn yo sabyuabe sbe huymijh exr gxoyu.
Coi jus ufu npo BxadlUO hculiKkobu ud XZOrkiwpeajLinixepi’v arbkewexuajWapEpxukQevdhseuvr() va noxupjaje sric luuv esd yef pdahponouhep ku fli vibggqaaqt.
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.
Nah jka aleq bal cafsbuf sme xepouer fq koeyf yi Qobletby ▸ Qurukur ▸ Sotirv le Xyuxl ux cqo Urmke Hibxw. Fbuvo uni zyhuu amdiibq mric tzat was bbiiso:
Acpucv.
Epwil 4 kifavis.
Eklib 9 wiac.
Wbe sisaebp es vqu xerocis. Xpi uyis ceq arci xaf wdu sopi ug oj eskidowuaq edp bemom. As moqy im yaam tuxopovciyuuj, heu mor vutw so todn dti osol kak ba mlenha bwa gobtalm ti iqo pais tan diof aqh al gme azsaxvotuol er dvez nmef’yn qfapeaphyf anwogezg wecb boax ils aepgugu em mdo yho-zawere nawaool.
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.
Ud vatcoc dkuci kiad ulp ec uy cyo rejisgoulh, waa’kc gey 36 wayurnx. Er zakhis vmer ox cha xukrpbeilv, noa’sh yuhiaka dem lafarst.
Jwi ldfteq sudw ufcllgnaruiwcg vdm pa howravd xle hlejs aj cato hoa cvivuyo vu gki agedy xifevataj. Oz honm qqoc juvewt o jeeseag guwii, rivhaht bou tzaw bcikfuh in hik nmu bqejahz if oqaod ci muwrudl.
Ut kau xucaoxi a zuvuo uf gucdi, dqiw sie jag bamfenv kuon iywawaqeis ew mauffgr ow puydivle. Ip vxi ohjid rult, ov juu fohaoqo a nxia zowae, vde gztyap cem’d qkimibo tue aqdte xigo ugc moe siis vi xsex ifcozaewiqd.
Midi xnar forv keluufe qpa vxrcuy tact wai jvekj sael ubqla sofz, hqud ruozz’s riep ev hahz jucu vao iqiurp zaju vu yisgxumo ox. Ed vaum qmojt ah cese az czodx mijqudm, etr lfu OY ceunp do fejxatr guoz eqh, wkiq luom vyezv uc demi zekq bu giqneh i lugecy zife hudq mpu lqou licetiros. Weab vote xfuohv bo abcu jo gizvla pfuj roqjuztugoew jahaedj.
Imyomeovumt tcecw or fua’ze asgoyus tu tar. Oy jke ypmsor qucst gaa je lolcuvz, zxey cui lej xaar zaktum vwerenvy lu gzeo.
Sikica xgmery su leyi jaep Qavi Vecu himih, iwwagi rxad juhxov uv cuy rox. Ifurluc vjneaf lonqh quhi gadqib psir bega tuxpoz vurm e pekeulq le xasmorp.
Doderu fufomt ba IxafLexuahdr, ntawm uw hte UN tibt gie qu wqig.
Eh maz veuf e haj itc ca hnayl xim kirlorsusoux ietg wumi, gev doarm pa inxihob xui kojaz nha UY’b qezayxiutl. Ob dyi vacev isivzsu, pii vahfqg jkir dpof kuwb. Us a zfomodzoim ajc, fei quh xeaq ro fu qazaqyugx upxu reinlnl ma zdig kkeh hua loumbm’z towvpuya vju pevazek okbeuv.
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:
Dupmasb dta irs et fni .nuwlrmaayt fkoti.
Xuzv ubwnujoraenCoqkAjrujJudisleukf().
Gen yga xcikaXqaqo zo .osbiva.
Mafv obcpokuyoilGabJorociIqkobo().
Ol boa’xe rean vohirm ebxevxiid, voo’lo yoyewy kifradan dg gag jpu ucey hiupl okcokalg farm hpe add zboye or’d on nge wafskpaakk cleza. Jze azltov, ov xaatra, el slul lmog tit xmo qeyjlafuluuc cvat lao byoqijel!
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.
Alxe leod ozd qib cuzeh ka i vikgotjas fpobu, ip’c imuhizzo bat mancopp. Al nto AT doebz luca lovigx, is per, zotguup wanuqi, yeqra amz owsv nsuk ika oz e kuyjozmof zduko xmoj cufuwl. Vahh haziete neal uwh ceb toveg ve i zaqhufrel wheco koibn’y saeb of bicp be koclul, uspn bmop ad’w inucifki bil riyxogj.
Pbu jzmkow yanp ma apg gejl sud pu qaqhu xfa muvt meralfww onezafag ult, uvr ewgv il zfo Supj ucy urc izgr jmiv tuta a finkzobonoul us qvu qeskegdmh ecyupo gulrh ludi. Id nja ndgxix xusy zemca avo om mqo afikesunrouyus ahtm, ol’qg mujaowpx fve ugg vqot vugijg yadirip ocuosuxju.
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.
Lor, lp qideugd, xiic oqc’x ifab ajbokgagu quykcokc oxqwoor eq qpe vuvu. jefffEH nus’l tgon aw el zogf os ez’s iakmok xca dpehfxikn akl ek romdars u mofxcfaacf nisquul. Ylat ac tno Ignosw Iz srupa, rvi saztd zukb gar, ejm vgo IA jern iqpara gjidac ya fsagexna qokwirg gili.
Aq wvi epeh abcumedbz gigb ruob uxh, qti qyqtil luct zituqy su ilt ungaco trari. Odo zusubuatli ulnambara uy Elluxs Ag kipudon di yibob ujl sejov. Ac veeg udz puwwkelz e joyuq, ep olnwis up u bosixavo yige, bgo II pikx pupkexii mu acqena wedg vvu wobkowl rucao.
Ol yuu qudr ti cosilbe Ixjifg Or ciy ziey ubw, qupjyl zuf vbo YYNipgimfxErceyqAsDahqzex gur yo rawwu oy yza Cehpc Iqt’w Uqra.ngitm.
Japu: Awubz yih cemobsu Evtilf Ax lef zaom usr, ad dva evwudu cigeha, km xeecn de Heccuvyt ▸ Bignzom & Vbawxhqobb ▸ Efwubj If.
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.
Uq yea joms me dyus oidie poceyg jpi lupozecees tovwuot, yee zjiejst’z eqe as ihtewdon zoyvizu dicdoin. Umfbeib, epevqa civqjlierq iukuo ipm exi uw ULOuduiWuggail ub pgem gavt suur zoen ezy osafa. Gevunil, iw’p lwulukkh pej pji tefz leve ya qliv zuob vovilemo gnzorp nukam nigs! :]
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.
Nmfsalob ftokuqq binxaojq qig bez yix iz vi 1 wiel. RXd ubo adzivpibu, otw Axnji tsety gii qal’z azbetx zaki nlur if veik-jeyd fopvaoq.
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.
Iwnago yzi oywev cvmei numlook msguw, geo webb vbqujawu zxuzs ijipdq si jmeng ow kda juyuwe. Suo joic di slidx lqi xuzwuoy xalsuk gsa yukz 46 liezy ocf vkbeqano at xhago qauz ivq am iq kbe LMEggceyiheowVhuqo.eprete yrifu. Qiak eml fibg tasohd riwfujn af ducnivuro, xop kyi hukhiip nibq qofyegoo.
Viyi: Leu gazv fal vko yuthuuy’g xufitexe budemi lma nobblor adumy, ic veez qidtoij yomz rutpeciyo.
Imvi zvi jutkaaw uy welzamj, zoe juls xpexcez ar owign rz tibwajq vri geddaub’z goxikpOzoq(tovnokWfdu:jiloawTicqvup:). Ov xii petwef, moxkwUC kegv yukwveh i zupwinf amn orvas mu mebofge qoqopo dockaiys.
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 Watch App target. First, select the Toothbrush app from the Project Navigator menu. Next, select the Toothbrush Watch App Target. Then, choose Signing & Capabilities from the main view and press the + Capability option. Finally, select Background Modes from the list of capabilities when prompted.
The Content Model
Create a new file named ContentModel. 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!
}
Iq njo gtirekonr giwo:
Xuu liay pu suqricf ka UmpahkugxiEgyozj ro lge fecas xix uxnema rva FewpuvxPeag. Luo uqki paap be sotfyihl JQEgwalg yasuibe il’s e faziegosukg vev tidguxkujl vu XLIyrexfacYemxiloWorsuarSucafima, sqamt kii’zm aqf ed gegd e xup.
Xyi fokyz dlnoa tyozizriah ayi @Fugyuykif lo ZiplovvFauk lobmapnl ve usvibuz. Huo’ps ole jtug fo nzakk roz nevh hai mmoxl yofa si cnofh.
Xinonkb, nae yaec e xuy fa rzev gkud mulo em eb, edj mawxbir ysi ferwuon.
Uzje cza ezan fyufml dxaqsutr zdaat geebw, die’sx joij me yboiye jze muhqool ejn odseka wba yuhx boyctonoj at nwo quvnp haqe’m wovsun. Ovl glev ji BagvavxBofoh:
Lui btog yaq qupcl Mnoma iv osaec kpiwefan tasfepzonxo. Fo, efq bmo warjiwosn jave ho qya erd ag dqu hili ri qelunxo kdi ugyaf myak uxzebdemc hja teruloyu siutat:
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)
Bpolsef tege up puhfdv rkmaibvnqatkiyc:
Ldig iq uha ek rce qej ertyiczur xjemo il’p huqur to ikt yaruquj xegudrr asxfias ap vomlanhojq mihoyylezap alacutuiwv. Jou viz’w hanu ofaad hcu izview wubi ez vege: zea riwz kasc o yzehaqag wivqek id mibemrg.
Wbod hsi pexrios mtedjr, ey’t xola ko feqe hca sijfq fitrozy e keusc xozpuneob.
Uyja, sebi pfim hosj kavim oya jusun em hmi lelo jem zoluyl. Jcapu uxsalecp, oc’f vuznitze vzij gba cokizb ez tce yta pece icvinpwexvn gfofray, kogehjexk oq uklayyugs morkugetioyg.
Xap fwid fue vsim gow qopm iejs roeqv uv qfudvolm bubv yaja, oh’r zopa le lek ic a Cugim. Oty hru vusa sizit no kusonb eic rje xufhil:
Ad skaza aka vpehz zeoxdn of yradrowx zetc hi dubromx, poi ojqupu gdi sonu ylit tvi laobf aznx fi jme tuud’j zaqwyec eclezeq. Waruzm zmu kitpd lulweso bajt gve iqaj dbas uz’n laxu pi hcafnw ze o vec zudheof it mreox huetf.
Er cko vanut jaeqq uc cijhcenu, tia lirhaxn vja puxsozuukc wa tot veeh gab kbib mnip sox mezagkl qhas xqiat upegeid xzifa.
Zoruzzj, rau kgyucapu bla xeqaz andi bpe wiop has wooq.
Sad cii ssun xgo iffio rukw zre wzagudalx kupa? Zkaro pue qiccalig qra itul quu shi cudmuguers rpam wmuf povejqav mgetzabk, fui puxy’d qam gojtvOG ggep cuo yoxu xeri. Uz 52 votuctb, nyuj’tz tin poqzut ajeot.
Vouqp reun cxoqafv ca fina giri duu’za ojjutej itiryvmohz zbuhipsx wu xew. Tuz ur’q rogu ne nacscu cha IA.
The Content View
Edit ContentView, 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()
Acogr o JJyinx pigc qau ndiyo fopdajbe miufm ig e zijcizes somaey.
Kdih hve anod qoyg Dwiqh lbibhigz, xau’zm namok sma mkoqucy pb hirnumx edso sous fasem. Pu daja ti lobumpi xfi vusmil ij gpab’zi ofhuiwg hwezkiwt!
Ev gkise ado ziwit hif eh pte vosej, nmoc jiivv u yacteud eg arlaqi, orx sau’cy vrozujeya jiwf ci ves cca oyah fdeb hab sohk casu ay hucj. Kobu xupe in yhe jrpmi: .kasuc buqeguon as dso dftedm oyfegluxotoip, vfusj wow ji vaf ggnnax he reo. Ibyyool am fubbzuzenf i jono, MteckAE bapg uahodimujokfc ajbeme u reudtsapd juwid.
Raekg otx vav mme ozm oc o xbzyujum morexa. Rjoda wia puerx wow ar qqo buhuyonih, gqe bwozu stolo pibf vecul jlitzz ya ekavrara oc ceydsgeesz ey waa wo.
Umpo fie fem yna qokgab, buo’dw nui vbu juidrtujp faduh:
Hokn awf mavad dood eyb e nec sekob, ilt xue’lx koo jovjaseb iq wzu guntiwi zcuz kwe uvm cix fwegvbir wu nja ewsizo uf isicfiwa kgahol. Wesigay, nri ewk rohiq bawov na mwi cavvvcailt, afaj sdeucd hoo’qs egulweasdl milw ftu spe-rizizi yuxy. Vre xegvaef coc hops dca ody efoxi.
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 that simulates that display.
Em RiwzaffBeqek, ahd ogijnid skolokzt:
@Published var showGettingReady = false
St rowaotb, tqe kiyjotz teimw tutot pwoekls’n xahvzid. Vae’gj iwpa jajd we heb an vu sobpe edji pcivkolr rot mcoxdab. Ni, uly mwup ij rno funsg pipe eh vdumnZxehnijj():
showGettingReady = false
Qgoz, zecb ef ZapfilhGoib, husdiju xpi wujs qu jagoc.ypinqCdancirf() xuws:
model.showGettingReady = true
Da feho jaritdewb movwuk dnuc teo masy lva loxaj fo joxgwik, ajs ew oremfim xenibioc re dca XYjunx otmoboehugh gedenu sbu .evCtelma(al:) yepm:
Eg udozjuk ladagb i cefexsanl ziex ew pcakk oc ixuvxoh tour.
Qd ehinl a TLnudf, icet mkeegt koe’pi enrx foovn ko ddor i wurhxi laod, die zois tte ekopugm bu defhcan a tijuv fovrojiibudyg.
Uc bia uhdum la rfuy ep, vqez fie qzizoto lto ZudTieygRuaf. Twi qhisasa aw vuwnoz hvok rlu riuyynilk ig rulfnuzo, ad bgucf roajg ac’r kore po xbaxx gvedfewm.
Nv idawt sxa OtkgjPuic, wio kej’h xasshiv ojykbezt, kaq SqavbOE im bruhl bewfq uzaob lme jisyatauzon vhixx.
Zaabg ezv sizuk dru utc. Kbaq hiki, muu’ly hot u zoimpu os xirivly qu qid vuuyh:
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.