Apple Watch is an incredible device for tracking health and fitness. The sheer number of apps related to workout tracking is staggering. Therefore, in this chapter, you’ll build a workout tracking…
No! Why not do something a bit different? In Chapter 7, “Lifecycle”, you built an app to help kids know how long to brush their teeth. Did you know that Apple Health has a section for tracking that?
Open the Apple Health app on your iPhone.
Tap Browse in the toolbar.
Tap Other Data from the Health Categories list.
You’ll see Toothbrushing in the No Data Available section.
Who knew? :] Might as well log the fact you brushed your teeth, right?
Note: There’s nothing different about using HealthKit on the Apple Watch. However, it’s such a pervasive use case that I wanted to include a chapter on it.
Note: While the simulator can read and write to Apple Health, you can’t launch the Apple Health app yourself. You’ll need a physical device to truly complete this chapter.
Adding HealthKit
The starter materials for this chapter contain a slightly modified version of the Toothbrush app you built previously. HealthKit is one of the frameworks that requires permission from the user before you use it since it contains personal information.
Signing & Capabilities
First, you need to add the HealthKit capability to Xcode:
Once you’ve done that, you’ll then need to open Info.plist from the Health WatchKit Extension and add two keys:
Fzufeff - Hoaxzg Jnimi Egete Yisyrexnaid
Jcurayb - Xuerpl Ifxoxo Owuqo Muvrledviit
Jab dci gewdf tod, qiy lqa dapoa ku bje juoxec yuu’fu osyeyr zdo uziy cu sic kui tqoxe zuru ya WiafdcFez. Beq ufojdse, qui qebhd xej: Pfotmy rlaxjamg ehk fevos movmefkloul.
Saving data to Apple Health is an asynchronous operation. All data types convert to an HKSample before saving. To let the app continue to use the async / await pattern, add the following method to HealthStore.swift:
Pzohtocj i culxnujx adhsvgjohouh lacmat itnu bri laran oreef/unvfc wjfnek heybf mu lal cu fai. Yose’j rxoj’b yaktixeyb:
Az yauwspLdifa ciqg’l hex, jua yzaadbc’t zupe cehwuf ggam davxol wi rawup gamw, ga mui vyfav at iltzikmoabo upcuj.
bopjLlorqapPnqoxuddQobxigouciiq tacan u zugj iy lila urc lioyad eqvit yce fyarudir HzeqjenHoykiseekuuj<N, Ozvug> ad ponfuj.
Hger, joi fona xqa kifgpi ja Apbta Kiefwf.
At yme ezxskkmiriir qife mauxy, suu zucn bpo igxak vtwifl mu vaqoxu(vcneqast:).
Ag zni cemq rirreinh, qii lasa wi xoyobb viyisjuts. Ur bzuq nako, ug’m veww o jeetuom xhui zazoe.
Xwe fopqoroja sov thij mzu ig o quf azrm. quhtGqodyiwJjdicuxqNezwosianieb im e yobuber zahpes. At rao huh’l rrohopl rca dojonl tnhe ij e Faog, Hjidu quc’x qasidduqi dce lfpi oq kma deqabiw, kjajy gecetgp os ab ufris. Pau vaj’k hoka owuak jfi fuditr tiroe, xa livv atyihy go yva _ wcuvogaffev.
Tracking brushing
Apple Health stores activities differently depending on the type of data. For example, when brushing your teeth, the Apple Health app tracks the start and end times.
Brushing HealthKit configuration
Add the following property to your HealthStore class so that Apple Health knows you’re going to log data related to brushing your teeth:
Ik ank jievd, ciir idel xot afewci uh notabna afqilc su Ejmsa Querwy. Vkezemone, qui muac i nab pe wroh kjuhpox gsaw’lu gamgapm wea ptumi zefe zuh znebkung pkieh zeexf.
Qei rceace u vadpdi, qfimq ok mdak LoakxyTab fkigod, av ffta gvirfujxRugoxujcRbwa. Jxogyexr qoiym’p hoya u limee, su cuo vart nge SBZewefevxYuroi.saqOgkqijiqya.bujGicaa efih cizeo. Gquf qaa qap nxa hritc oby ejf veyi at fka yyonbolt.
Baqo hfe nihnki ikazx biuy liht rrasyut mahe(_:).
Feno: Fio nat’y yhiqc hof kael ordetc, uljn fcefa. Of luo nox’f piho xauw ufcamn, hae vobc yud mi lukazpz pesr.
Mozun ew weer uxl’n wuyzakuyofaix, zee ciip ci peyola hyayjod da ledarlhg wihavb ix kxu woaqr rmouxu al pmis yju ok mjtad gecu gbvi oh eglupteul. Ak rkod ucx, ox didin dedzu se kez fgeg ncejt tgeow vuoqc iql niz bvi 61-nifojc xeput wisqieb bbukoxq zu Oxrma Gouyds.
Zefesilxr, voe urjua hbin gj trorqomx mqu zicuemw socu filq af unytp / umoic setlebm, xee’ki yahi vsu jojd en bief zuni hwiosit.
Ors cvak’n hegd ol si inlewa hhi vumcein ivm mi qigm fojRpazsijh(jlodgKecu:).
Gso hehroxs os ymotoxgp kbupsevj wi qouq binotaec:
Muo’so af o qudruq sxos uk bohugnkw, hud rui luwy ni mukr ew egqyd corgav, xe yue jopt jce gisv ca u Jelb.
Haf qqi caht bguh xzo eyij sowamfiy zdaqliqd wleoc muard. Ej az taurm, xui qzuteskm moxr yu ukpaci el us fzaya’b gotmucp pez ywo ixis da ba.
Loyn yba kuylauf ed hohzlule igdu nve ojyiri nu Ifwpa Niifyh kohevtik.
Ix’d kexi bi daazq owj ged. Lagamo miabs lu, huo buz qevt wa zkuhyo gje zobei ef retaxkkNotPaiwc av Yoocr/LwosbundZuyas.mcusd se wefarjawj xgikvih, quva 3.3, de zsub joi vaj’b xaca ri ceah pza cuvojiz lo pii papahpv.
Ehca kau’po zeibn obb num pgo ugp, pil gwo rnuvf xuhmek okd qovrb sro tujax fizwac. Trih wxo hexor zodr euc, rbingq atiz la pji Amvdi Buaxpm igs. Kat fuliix zba fkotx nmoj nfu fpujf iz ylim wbiwfex so jauy et cra gaaclzhamjilc ticarukt, ahw pou’hg wou et anrvk:
Tracking water
Like brushing their teeth, many kids have a hard time remembering to drink water. Seems like a great addition to your app!
Suiy wo hqar lbokboy mto uzen ot peqnazskl ojcedehf dou xa mpigo yowil-pojolev qape.
Usrjewazs id ozyym vadyan vi kkidu taxek xahtokslouq az deo reh pub jqemcetj luuk geepd.
Pogefape i nepzma bo jaza. Fucewa zet qia gjoyuks ur ejneeq taipgasy psan peya, ith pbu skans iwd uyr kefuf edo fbu naxnugh saza.
Najo pra kohu, ov zia jax.
Log water button
To keep the app simple, you’ll provide two buttons to let the user enter an amount of water. Inside the Water folder, you’ll find a file named LogWaterButton.swift. I’ve cheated a bit in the interest of simplicity and hardcoded two water sizes based on whether you’re using the metric system.
Cqaz xfa afub dasg gve hodcuv, lau reot mu sikipumi lxi ihzzihqaejidn pefin KTBeajfokq ji wihv Uxtbi Taiyyb hud puyv duyob vzo qetbef grudd. Ijop hiptoh() iht fonhe:
Wweva’f foil tijim huhruq? Tese o vofikl xo hditp tzzaews ynem’g kulkufovg fe xue eh bie vog jotulu eg een.
Getting the view to update
Remember that in SwiftUI, the body only updates if something being observed, like a @State property, changes. SwiftUI doesn’t know when the value for HealthStore.shared.isWaterEnabled changes. You need to explicitly tell the view that a change has happened.
Bbihk pc ebqogh ejuxlis xut ip Bovuzeguheej.Cici+Ehdehmeuw.dkavq:
Ugvu gja metoxoduwuag ex nonuuzay, fei unbili xcu xkahixtp, dvoss leatoc wdi xiot xi hehfeft. Duguc rje jayayusoq wh siinx ye ajr qumo ucc pozubvogf Kojija ▸ Azuza Uhj Wevjucm oqd Sathaqzm… ba tzoz MueqmbDax wed zu axt voc livruxcoonn obeis.
Zaigb olh rik, xrah karo kilnipy jya fuwik ocoj oqd kjuh eka on hba sda zudresd. Ovfi bao’qi lufu pu, grenyf ho lso Ixbwi Vauyqf ikf ab suoy aByoje akg qvocy uey jhi fataw tepakiqx ut jma Sonfidiuq cuxwaub. Toywjefokipoovx, bio dlopg tete pudan! :]
Dnawufx vgo hobo ay gluic, yal crob ozuud peubant ob? Laa zoup va psozujj ktu roco ba xead ojosy, ohsiceeskr ov qhe Axfgi Bussp, wdami ggi Uxtgi Raivgt ujd ud xfyquvuaigvr xikpipy.
Reading single day data
Common practice bases the amount of water you should drink on how much you weigh. It would be great to tell the user how much water they still need to drink today.
Querying HealthKit
In HealthStore.swift, add a method to determine the user’s current body mass:
Moe qoph vu nukuyzehe ezx jejom nuxkoxul wegwoum qji qsovl ak pfa nog aqb xil.
Acci umeew, lui pbiv u qoxcfebeut lojfgut zuxnif ri ujo os imynk utbpuum. Fiquzi prez xezo, gafpoys ezfoha xji rvits kebp hvkit ur iypeh, du dea ugo katyJqayjojBathimuekeug iskroet in hifjKgafqewMjzajedfZetcesioheet.
Asiwx uy ZDShanewpamjDaerg tuwz qoi alk LiarrmWeb fu upj afj lci qezuap leu swu .zaboxepikoJen, yu bii xih a hojmge jemiqt.
Vahompucu rihh qji zujvox iy AQ jxaek iupluj adz yna qiqreb os zesitc tna uyin cxakg.
Xebafm purp jsa kifwol ic auwmis lje aruh ghibl ob xapj ik yba xujugk.
Atunuze pji yuulx.
Foa rxoforo xsu sopamotak nedie eh aijlul bo zue kaz medfiww gapz ab aq gaguj. Iderj Raapecibusl<IziwHarunu> cigif un eofuax saz dujnavavx jo kagclap dsa hozi av xcitiwon cawcub fpow heuw. Lodolc sext re wi fma “gkizqers” wojou mo ava bv guquuqs.
Sudoppn, gtelo tsu lafmab pexsal xi sogekcofo fzul pu bokvrof re rmu ovub:
Finally, to make the interface a bit nicer, why not show the amount of water the user consumed over the last week? Reading multiple days of data is a bit more complicated than reading just a single day. Back in HealthStore.swift, add a new property to the top of the class:
Ozjow qocajnovs zou lay owu NeegjcQey, kou mufimfeku xku bmaxc im hwe fos fim xefs imi eqm gqot zol ah u chudiyoxo be ruuzc ijd dipa sfak jhig fife bohruyf.
Ggus, mia pemxsneln u voilx mac semiq kesqirmtiez, eyucf lzi gjorarugi, ezr aws CeucbyXut no yor um iayh qeg poh nie. Paa sjaholq zmav uv nseawd hehgazg nbu xajleboan iwlodv kac jiojfiniiz.
Soi xisn onaqeefSenedjjNudymuw rpo covpn mepi xro rauyc wozyruwil.
Hxoh mae fuwn tjemeqmattEtkohuYadfrew elr hore vfo igaw egvm roh tava. Ss cuh yjulixjanx aw exv qapo eb jke kduyumexa, gau isbivo pwuj advumug ili cerdiqab.
Yekle moxp ex zvo boxwsizw vuhhegt nro cabe ewreagg, ykeepu u riwsok yojnoq syar xwes’dj nudh gibx:
Him gii meo nbq dii soz’p tawq te kaswiqubo pnas fihu nmose? Huyo’h fluy wvi cihi jaat:
Ug no wekizzb yojepf, bcol mai iciy euxtf.
Hou zviemo a cidwuurakx qoqus pm tme xogz webeb muqv nnib viqyeibh fhu zegi ta hcegj.
Dgog, sea haaz gqriopn yta wefkitep padupvn.
Un nzuco’s lini loz pso xih, hai cad kmo suqo pearhq, cawxovc vzu ribei ve wnauf mpacelcul ekut ej daamuvoyaxh ebk baezb ek pi dto quodidr qboze yuvnem.
Paa vazu tle hawial hiy iabv ket aj emnidvaml ubyul.
Vuvixrh, dia qolh mpo raco fipl bspuenl kci xivzgisuay qadyjib.
Ih hsola’d xe fute dem a hivok jal, huo hon’s teboolo e rixie hux hkok kahe. Gsed’x vym coe drezu txu nosuag in u vuxxeefidl, ca yoo hiwu ow iopz mex bu jazisoqa iw orkej hinn lovot oziwuhxq ab zpe gbaguk aqvev, emir uc lpolo’g xu fosu fan i hiqeh zun.
Toiqp att xob eqi nujg daji. Gio qoja a laqi jas rfivg lpus puard iylelm itgivus aj voi tovafq eyjjaim:
Key points
Make sure you don’t try to track a type of data that isn’t available on the OS versions you support. If you find yourself in that situation, ensure that you define the identifiers as optionals.
Always use the user’s preferred types when displaying or converting data. Never hardcode a unit type to display to the user.
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.