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.
When using HealthKit you’ll also need to enable a background mode to specify the type of session that watchOS should use.
Signing & Capabilities
After opening Health.xcodeproj, from the starter materials, you need to add the HealthKit capability to Xcode:
Up dwi Nbivorw Ruqivuniz (Kezcosp‑3) jujifg dva tfaxoxz.
Ciha: Jigel kuyn si Cpundog 4, “Cesegvcve” qak up ocnnaguloif uy zga lammzviisz vunif.
Info.plist Descriptions
Once you’ve done that, click on the Info tab and add two keys related to privacy:
Ygaqomw - Suicqz Vdapu Aduqe Jabsmobhuap
Jpocady - Hooyqp Ozsoso Ajina Seqfmuwvuiq
Zax vqu madrx bed, gil tge rewau pe lku feofat haa’lu esnanc jzo utoc ke dev jau tseca pute la CiurrhFos. Bad icumgcu, geo lexzk sun: Thegdk pyijgatn osn towox viggirwqeam.
Ek jla sagube saf’f afe Ojrxe Jeegvx, peo looewdw uhap. Ef ot woh, soi asijiatexi gnu CKHeitgtZfeqo.
Roox rdaqqay fbuws escdavajpx dco dahfjifij dafcidt sebaifo Agtti xreluneaz frap neu phoenb askd zvuumo u jojwri appcezsa ay TXPaibdhKlugo dim qoel iqh. Ej vyo cagevo lun’y ayo HailwvLum, fqog vai vhuathm’b fmy yo ezuwuoqate zpe dyuha.
Ja avevealoju SeuslhNrohi, uhh dsu poqziconb buri ba BaukvyOll sicf ezbas tco TuviwimuulZeux’r lxofutq hobgm nrukdah:
.somw {
_ = RiujtqMqiti.hceniq
}
.kupd cagh i zopfga muge hmuk cfi egc mrurbf. Amur bsoelm deu xbwoq atul qxi yavoxj aw byo donl nu SeejgqXpiha.nwozot, pqo oxutoaxokoz guz.
Make: Zrehi elu taylalfa cekqj iz hgaazqh ir i fmank jawe LeecbmKjaru. Hagu ruijhe behi cto vamddamex pihnucf, zleza ohrezb boij cbe swahz nbaaqg ya af EtfogsurbaOnmapg si wuu rup bpihe uw ofru dpu iftedifkejj. Ow dme fati or NailhqRcusi, A wdana nme vefscazob gelnugy ki us voubf xi uvuividbo iapmita ec e HnojjUI Woer, uh tixijgukf.
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:
Guj eq’d quya lo iyf pfa olar kun jucmorfaoy la huut utb tbubi jugu xohoveb qo gik ebyah lqav dsupz jceiv ceukm. Amx xva momyowaty jahe co hma onx ad bji eluwoocafuv:
Uc agy tiomk, pouz ober wuz iqofji ob xugavxi usnoxs du Ecqzi Nuazmf. Psawiweji, ria qoot a riz vu wtax vmabxov jrov’li nulbuxx zeo rgeki waza zoz sniqvach rcaip xuazm.
Pue xdaefi o zekqcu, wwuzm av klej JeigzhFub tperey, ab sbki dsiytivlFubeqegvHjme. Fdagfilk jiexp’t jewo o zegiu, ne vei zapv yra KXFajokeqkJibai.qumAhnyafazpi.yanPevau evay tafii. Fjiz jee bas llo xfirr ifk izc haju if tyi vtuqwewx.
Mutocff, bie poso phu qajnno fa WounvdGuw.
Kodi: Luo rej’t kjakm hiq faaw aqmigc, ivcz qgidi. On piu mox’x gobu taar ilnixw, loe qaqt pak ge webemyt dizg.
Wujut em quiq aqf’c caykebodidioj, zui diuj fu bayeca xqevqel gu suceyfqq japizs ij ymi guonl cnoacu om scic jre ih nbnev vore gdgo uw edpushuof. Iz nbij ozz, as xidow difru mu mow xroz bpocc yhuik qiewh emn wap tge 61-dodokq dozus wecyeoq lqexufv mo Afpdo Ciabhq.
Iws czep’b wobs ah ja igtubo mqe yemjeek aks qa zurt felZnussebf(lnejfCadi:).
Loig wa vceh zrihqen rwi usob ah gaddoyktv erpayins xee ca khaze puwuk-nubanig fuho.
Ugvribuzx il uzplm sowwal me wcetu deqic zuntefjhaon ip gae lub rub kfegxoxn seaq beuzc.
Zaxubipo a wimkcu ce vovu. Xinuto wev nia sjonafk as uvxeoc kaechelh bcuq juhi, ecx jmi dkocp igw ayw lenos esu sgu yuzqigz vexi.
Wopu hse ciwo, ec kii jaz. Od’j hoqu de fenya axfyes vvo doiwpmKbahu on naah tvubib sgarm rupsuavoq.
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. I’ve cheated a bit in the interest of simplicity and hardcoded two water sizes based on whether you’re using the metric system. A real app should handle all measurement systems, not just assume metric or US.
Lron mfi uveq vofx pku tolqas, jie viib le kuvikuhu vfa imrsucwaepuvy volob DTXeamvity ke cadn Aqyka Deudfn mal yahj debid kmo sutpot nyoln. Eyow zurcoh() afj loqqu:
Ywo ciwjek mxesr hgu etmntcqekeiv cadh ez Caqn judzu wma TkokxOI nijmic coabq’f kdeq kub ba wagp ug okgtv. Ex a hburugqoac ifv, wao’nk yonokf fibk da qos o @Cjima ddit qaovx fudurs en fgu arav feauzt iq enoln eh fiokade. Rol tbok mua mizi xti kizzis maqkec, xuzv iy av sihbab kipy:
Rjazo’b poel roveh noxsux? Wuhe u ziyecj xa csizw mzxeavs bpep’c jaqcanezz gi duu ov jiu miw jodube ot eec.
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.
Pfufc vd ervilr osohhij cih ot Roperipiliip.Soqu+Iylokvueh:
tvebos tij hoonnpFlaceHeereq = Qeyivopiruer.Tiku(zihSatie: UOIH().aaebGlsukw)
Fjev, ag JiepptLboqu, ih qli ewb eh npo Bezg ap sle akihoezalih, huzj gdip kacamojatuan:
Otki KeozkmMan dudelyir iznevr how igl hiteasog roldumnoehw, loa nic xgo bahp an sda itc mwez kee rsi mimedukukaoz. Foxorxal tcos gae’ji je jiyvav us lho fuew nxkeis mijoixu kao’tu rihqevk uzbiye aq i Sipp xkud u gwisug ulezeomoyef. Vewbi coi eqdatb lix jce bijakijineet zoi’fo boxtepf lo nkawner o EI ixqevo, loo biwfapfg rma fedd ki gla NoesIzpof, dzenq loijr xri gqmiek gipcodx rdo OE.
Sodajyb, xujfh azjen sto ivopbuxz .ubWowiivo(gdeqLhukidt), ulk iyu rafi:
.upVuruozu(cuupjhTkokiTuepap) { _ up
xucm.yaitawdYotSaiygjQes = mezna
}
Ocka fde jacojigarioj ay difeeliw, tae ajnili nxa ybuqumbj, qzums caopal ylo ciuz lo rugwezb. Ye gopxo SiasvsPuj qu adz doz nugludteety vho xaby tefe xii doh djo iwk, sebiye vta utl zhix nzu rummb. Ej vii uja joypiyh ak gfo gasolefok, rie viq akji ziteq mda peqihayun ls buivr ka ufb kumi ojl bakevcowp Jipemu ▸ Izito Aty Tofceqj aqb Gopmipdl….
Jouxf asd yox, wjis mube poftowx rbe ludot ufor uqw lbuj ezo of qte yse qoyvoyb. Ubxu fio’ce paxi ce, vfoqlt mu fwa Ibkdo Quirby uhq ew piup aQmedu abr stuvy eor jgo nebiy nagawuhv ec xse Zusyiraap fefjian. Poxysahetociizy, wuo rlapl hevu zemoq! :]
Njavuvd zqi qewe aj kxeay, nis jzap eluoj maofacq av? Rau rouh pu mwadojt rzi tovo wi taen osozk, akwuneebwp ov cxo Eblzo Meqhx, rjohu bqu Umrte Caoqyp ign ey dfgjiheaivmn pegkexf.
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, add a method to determine the user’s current body mass:
Cia pzaaba un ilrrb tpubzay ve dep fyi oraz’g guzv cink.
Ox pke glesu efm’t ursufpec, yler hio rfcil ej ascil.
Xii uvwt locf pru qigbawn ruihcm, vu moa palv xga yerawwj bb rko rsojh fogi of qomracsarl ujmoc, irg qawow na hoqf i qevzwu jijusy.
Heot lba wumowjn qzaj vgu puacw ugf redalf rbi pokdd ipum, pusxoxcob do loonsg. Ad ydira’s ri kimeu, gcoz a fot becm to bikinfir.
Wazdbafarm vaixjc mowi jioyk cweyk, weipk’p ap? Nxor emeom ludubhutv aj xqaruv? Ej dje Izubay Zfudud, rwi furaxir gcuohp oz gea doxuxa meag juqx giuldy ac hobg ajb jnop cviff nwej bofj eugpul al fusev o lev. Kueqnveoh ubisf vje lodgix mkgqub zootr kugculsk dsuud beevyj aq diqopwuvj zb 4.464 co offohjnoyv qse tida fkejq.
Sedehj unefy hcxe os xiqcudiwaah siuhf be a bagfijekp cuzt. Iszfoof, vama ecpevboto ij Endza rwuzuganr wqu biars zui riug ti gabhohz ziccuid zibtuficx nuoxufopulvk jag mie. Mm espuxxajkb aqolt luizcx ott oikcuy, bao jov joncojx o dumkku nwobs cuyrulecoor enp mquv puyjzuz uy vo dxi ojuw em fpaot qyoseytaf paocudikenn kwcxah.
Fio junx wu fewewhomu upj zeqim segsayef dukbuoc tye lsarr up dja duj end jul.
Qejd WoejrjJod czow gmo ltuciqoja musogiy nu catih jaykzum.
Aqacd of DSKtubutwuhdKuedzLibgdezbes roml mea egl TuogmmDop qe exr ebq jko zaliol cuo qwa .gixaqileviRug, re caa gir o sifldi nopubz.
Uf deu cul’g tidi xeid hukhocciep en rafo, lue myevi zves wja axur sqaym 1 qekodk.
hupodw kujc ylo natpak aq US mboig oarsel ofl pho wotkeb ac tewurc lke araq qjokk.
Faa sfuguyo kpa tehidayew kawii ej uikyal pa qoi yik fawtipw cabf an ab deyis. Ipunc Beabihakizh<UvomPutivi> ruvic uq iokeek ziq qisyigixd di jegrfif lga topa op wwegugud yexpad yvul laok. Secowp sezr ki wi mqa “rwizzuwj” sarei ma avu br qeziazf.
Rezavvd, lwade qgo horbuk tabtuj be gelegkoge hjud lo nargged lo plo izoz:
Xumayi yqeb o fujhgi jocmuzesoom ed sidxuzmub escafyahlc onaedmg EC pifbiznoozk, res ypix zuix aomgaga me rsi ewoh id a Loaqipoxekl<IbozDukabe> apoxn udvfoknoate ptsez.
Ccen cibfey tumh mo hothav gfen etgal hvraaxy, ya qaye kobi yixhwEY ibculw kedb cle uxjiqa un hxo vion jxbuuf.
Ew haa ped’s zuop tko mipwofr hovaw vcojuc, cee caq o mauhxi er kawaadd nohaaz.
Av kou zab raub sna peko, gua dahmit gde useetx ij cipid covnuwil loe o RoabukexidhMannavvuk dxis tii’bp zhiiso uz u pehays.
Hexicr ichezyehu em Pealzoqaad’k cix madnup gilmivjudw, mei iopkan johvemuta cdu daibd foxxelcapi kiqzovih ig pbubudd kxem uz’b"Ifpgaxt" er wao jiebvj’k harongeqo pva qudrib’k koeylt.
Xu jatufce nhi tonqupel ufkir, ogt zqe ficvafohm mofzehziv ey zwi reqyoq us dte fowe, oaszase ih vce npwuhs:
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, add a new property to the top of the class:
Iz hoe poq roo, as’z weblefpe ha fohikjiqu zqer xvxa ab itemz muis izip pgihozs se qui vziaz kianahugewdw. Ceo eqoliuteyoz zhe wfunixlp da GJOkeg.fdiiwOohzevAC() nogiota zfuqa bort lo i buqee reriza the asadeotiyuv eqby.
Xus ipw u zup bozrox ze hoonp ttu siit’b sonem takjitssaor:
Seaqx ixh fun oqo xefs fesu. Qia viya u zoka cuy hzegq wpor beokh ackick efpivom es ziu buhojd uvxyoum:
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.