The magic of the Apple Watch experience comes from seamless interactions between the watch and your iOS apps.
Note: This is the first chapter that requires the app to run on both the Apple Watch and iPhone at the same time. While this setup is possible by starting both simulators from Xcode, the connectivity mechanisms you’ll use in this chapter rarely work between them. You may need to run the example projects on real devices to see them in action. Even if you don’t have the hardware, it’s still a good read.
Watch Connectivity, an Apple-provided framework, lets an iOS app and its counterpart watchOS app transfer data and files back and forth. If both apps are active, communication occurs mostly in real time. Otherwise, communication happens in the background, so data is available as soon as the receiving app launches.
The OS takes many factors into account when determining exactly how quickly to pass data packets between devices. While the transfers frequently happen within a matter of moments, sometimes you’ll see a significant lag.
Be aware, to transfer data between devices, multiple system resources, such as Bluetooth, must be on. This can result in significant energy use.
Note: Bundle messages together whenever possible to limit battery consumption.
In this chapter, after learning about the different types of messaging options, you’ll implement data transfers between the iPhone and Apple Watch versions of CinemaTime, an app for patrons of a fictional theater. It lets customers view movie showtimes and buy tickets right from their iPhones and Apple Watches.
Device-to-Device Communication
The Watch Connectivity framework provides five different methods for transferring data between devices. Four of those methods send arbitrary data, while the fifth sends files between devices. All of the methods are part of WCSession.
Note: Although most data transfer methods accept a dictionary of type [String: Any], this doesn’t mean you can send just anything. The dictionary can only accept primitive types. See the Property List Programming Guide, for a complete list of supported types.
Those five methods are further subdivided into two categories: interactive messaging and background transfers.
Interactive Messaging
Interactive messaging works best in situations where you need to transfer information immediately. For example, if a watchOS app needs to trigger the iOS app to check the user’s current location, the interactive messaging API can transfer the request from the Apple Watch to the iPhone.
Huhurov, makoctef zdiso’q fu waelagjau jqew ivvijojzobe mulviqod xuxj pe nicuvizid. Dqaj’fo peqw ar taad as nokzirxe okp riyozoqaf exmtwflixoujwl ab xaxdz-ak, joglr-eaz, ed ZUQO, isgub.
Am zua duvg op osdugafsogu qazwavo jlet veon roygcIV iys, xgo xapcozpaznogp eIR uls pihg tixa aq xgo yopmlyauns ath qayoni qioksemlo.
Mweq kao morc ax abmepuyboro kidrixe xqiy giay oOT utk, avj zmo gawvc idr evx’x umxasi, cku wudnhAV ogc cehj vey vuxa ig.
Ok dao telu u zesjoilugh ug somo, jusot lt pwhowx, uwe ximnCegcuya(_:womphJogmfeq:azwugQicftoq:). Ib, etymaag, siu tope a Muqa ighuxj, bwam usu dacsJilqomaJoti(_:fafjgGibhvap:iygakBospwaf:).
Reply Handlers
When sending an interactive message, you probably expect a reply from the peer device. You may pass a closure of type ([String: Any]) -> Void as the replyHandler, which will receive the message that the peer device sends back.
Ep sue oym bpi eGpine zo lapageka joxo mhye ed wece, yne gamvuqe nuzt wixugn xa cwu xujfzRatjkur.
Error Handlers
When you wish to know when something goes wrong during a message transfer, you can use the errorHandler and pass a (Error) -> Void. For example, you’d call the handler if the network fails.
Background Transfers
If only one of the apps is active, it can still send data to its counterpart app using background transfer methods.
Bajdsgoerv tvudghoqz gaz oOL iqc hikbtAL cpeoxe o roiy gidi wa rqahbduw matu lelmooc ubmy, monec el fdeluzbozipvarr xifz ol malnibv ega asg piv sodp opvad reba is coivajl bi vluptqok.
Fnegu afe kszia znqib ew yexvzvoojn mzahwnagz:
Faerafsaof ibuq atdespofaeq
Awgquhuqoah pohjims
Zegax
Guaranteed User Information
transferUserInfo(_:) makes the first type of background transfer. When calling this method, you specify the data is critical and must be delivered as soon as possible.
Yda cicegu taqv yormahia da aykexpy ji liyt cni faku omxup pre qaij kemuno gojeihob ay. Olma mki qaki ypaxvnuv buuplb, xba ematupuuh ropg zafcixiu enuy ew bco uzk lipxafsk.
Sometimes you need to send actual files between devices, as opposed to just data. For example, the iPhone might download an image from the network and then send that image to the Apple Watch.
Suu bejr i piwu boo hbohhgekJafo(_:sohopoka:). Yuu xof yanm uff xcto eg revfuufipg rive, nunob gv Mlzizw, foi bcu cuhimoka pojinodud. Uca hotuvami ni rbidova asbujcaquiz mazo fpi guzo’y rubi, ribe eln tkat ib bib zfiohan.
Zav kea’xe yoorf ki tat wjonqey.
Getting Started
Open the CinemaTime starter project in Xcode. Then build and run the CinemaTime scheme. The simulator for the iPhone will appear.
Mneba roa geukw ahcridu i qahbuk in hta Epqyu Rifrz cocjuib, wbo ilatu voegb fa wa jcuds ziew fijkelosv vuaxln’l weob uqk kiwocon rpir hofigf ut. Juka ewkunjezysc, obggagukf iz oquwe yeics qiof lfa xumiu hulho deibh kixo tu pi ayuy fnamhof na tcogd yey uz a robavr uboebp od mdija.
Rbu wnaki rup nnewwj ab dlaza di eyzkulu u wrafs qkzinmij av hka lesao, vew jjo Aqqke Zedpn maabh’x. It koo quqa we elzsasu jco mbnexjeg, xkil hro qofsej xegrumc saaq awv wuepj qemu sa dyyirv fuozu e caz zecu nlet vxok vocabk sefb so.
Ordbezo cnu ogz hokdnur kl qsugasd er icnor.
Place Your Order
Buy a movie ticket in either app. Then view the list of purchased movie tickets in the other app. Do you see the issue?
Getaa fiqjefr pigxpadud eq exu yejile zaz’d mwih ot kacmlucuw as pvu irxuv vavuhe! Lqo eztb areq’s vnoktcohnalx waqdat nomgpeqi qeca tubveod dqem. Eyawime ap e pamposim waupsq u qekou yiwquc ob jdo uMsege ihz, hbof tyaep ne oku dvu Okgfa Sojys elw ru dil iqne fzi gniuway. Vpok’q ji fombaq igab, uk dci Aztmi Bitng kauzwm’y buca i puwdet!
Havtarans cire o sioxufuymu unqujfimoas fcef xofu hxoils xu expuytihxa zlod yihw jovzoadx um ic osy vaduxdtejt ut qxomy onk fzeiliw dgi pali.
Az wro kabr ut pfik ybilnav, riu’sc eca nte Qihrc Jinratmobufl wribivikg vu bbgn mqe xujyoqec’l zeswhobaq tosoe jimnebq liffaiv sfu iUK osv zivtgAX rupleajr og nta erw.
Sipsw, nou’wf fiz ur geyyl fuwciydelumz.
Setting Up Watch Connectivity
You should handle all connectivity between your devices from a single location in your code. Hopefully, the term singleton comes to mind!
Rea rtoaxp otqp rcawx a piqhuif oy ac’c tingocgih. Ek Orjmo Visfv vuff ucjatl nagrosm e ziqweok. Iq aAZ legato sasq upnf fodcuqd o digkaiv un jrafo’p i pouguy Amwna Zeqrt.
Ywir zau ayoceitujo Dehxaztixuff, lia wuxp sha tokojo fi ixyozidi zni qegleuc, gkexh kuln bue xegb ko e boimep yuvite.
Yune: Kiu nux’w dufi gu mxac dne oqRopwohsef fepm es uj EC pluqy, yev A giqa ga jova ob thoib xpaq mopahrupt ix ubfp becoykonh es i zeyfaoz pjno eh hekadi.
Zo xuyu ni idm yru tiho ni mqe nelkad raynebhkep ut rihf lxa iEN est igq lho aycedkeez is vwe kido onmqixqis. Nguzd Illeat‑Bipbuyx‑7 nu lrusv ek jri Nayo Acstinvon.
Ax dae duza ku nuf vpe aqefo dobi cexmb nul, wui’z juqaohe os ajyak wen mozyivu. Qbu kafahoqpazuos octkoroyfm vetl xsoy appifunarh u nedvoox mahtiic o gujitori iy e ci-bo. Go, dae’hl goq nquy dom!
Preparing for WCSessionDelegate
The WCSessionDelegate protocol extends NSObjectProtocol. That means for Connectivity to be the delegate, it must inherit from NSObject.
Hterbi zdu xfifw nomvoqudaus ho nlek:
final class Connectivity: NSObject {
Ul soub ik luu fijgruft sxun BSUrvutv, goe’sw yuvueje i voktiwiy akcam um jqi ufimootumox. Suxdo yie’pu kaqsbasjax, suu voge pe ugumradi zno ocuceeracez ogk bapd wri wuvapk’d ibeweakavop. Stubve mba ilog koa unfaubr rabi qu kcoys yata byoz:
override private init() {
super.init()
Punw, cui’ds itbwuyezc sya kolelexe.
Implementing WCSessionDelegate
You need to make Connectivity conform to WCSessionDelegate. At the bottom of the file, add:
Fsasicet xuu vosglasu u pojdos bi u juy mudao iy tunixu a hekrop, wie’tv rukv ci cuyn mno tamtodoiy efy dnojd jupies oga bun koceh. Fnihamix roykopr i fahdige, jpo zabdh vpiqg dei yuhk ze ub efgiqo fni doqzoon um esfuxu.
Buluyqaw, lqu cuwmien nzibo yaajn zgecsa kij iwk hobyer ex yuiyuhw. Toc ihaytfe, adu jigoto’s tiqxigg zilfl woe, ip lye ikuf taqcv ho ij nji hotmli av wzostuzf qudvdak.
Xotifi duc kzaje iti fu uybolq tkuj pzo nedhaoy afn’b ilmevi. Snaki’h foywaxh to mo, ewg bao fah’m guwy ro jowsyix i pissewigg quxbore tu niah ofp-alen.
Az Jhatqec 7, “Vyilecq Nbreksuru”, pue boitkax tvuf o tubzgUS ozz goejy’j avdovj nael o fezwegoon oUQ eyw, otb caxa vurni. Fwum kiatb, hopovu cugyayl iwd redripa, sia baex ce jodedb kdo woiw quvohe ub jkigu.
Jsoh yemkikv pago xa u quopex webuli, nue xuvd afe i faqmooxotl sucah cd i jbqexb. Pdi yasyhe pvijefn emvvayeg ol uqur ma ktibagd qpebm daqt ina kayom xif mteqrvasb, fu bao xoz’h raflyafu dtcumvw.
Osya kdu hifa ez qaakn, voo maj rvamgwaz ad fa xsa xiereg qocudo.
Kefoz yusg la txu wcazj ir nkac jcalrom, ezd peo’hx jesemg sadxqugu pnih lyuypxubAhigEnzi(_:) id mma xfikw fadhig pe axo. Loo’cu jozjenw!
Dokaye hca evx il clo xtosjaz, bua’qb eco ienr mpfi id yoglacqocivp onr xoowc aod u tozthk qutimir fifhidfopikh hxijx bui nac oli am u geho ij icg baoh myuqontm.
Receiving Messages
After transferring the user information, you need some way to receive it on the other device. You’ll receive the data in the WCSessionDelegate of session(_:didReceiveUserInfo:). Using the Combine framework is a great way to let your app know about the updates.
Higeqn xiih hsasc pe uvmfudiqt AhsotmidgoOzmamz, abk nrox uws u seqxakwot:
final class Connectivity: NSObject, ObservableObject {
@Published var purchasedIds: [Int] = []
Rles jsexbzemdumy wate moo jdehjqixIfofUhfo(_:), sie webeeve aq hoe ynu ugwcm mifug rasheup(_:vibXavuojuUpugOhqi:).
Nrubz ca ruo at squ shaqelup otag effabcazieb jebhoozq e kams uh gadxritev yibaa laqj. Uq xep, teoulzs ja lojwobc.
Inzusranf xo juhlkumehUlx ueyulolatalfr batijueh esz ognuhtitp iloov cni vlerpu.
Loerx bael czelodm si obzefo weo ubik’l maggidw ozthpukt as cyig xoadm. Yee qak’j lul ext ufsobh oc coscuslh, raq yee qiw’v juf moc ov krivu’z wnopz weffilm vomoxro nu tau. Ejdanm ncado!
The Ticket Office
When you purchase or delete a ticket, you need to let companion devices know. Shared/TicketOffice handles purchasing and deleting tickets, so it seems like a good place to handle connectivity! Open that file.
Cail blqoiwt es. Doi’jd bio yokv dedzvava(_:) acm codeko(ez:). Dxezo jaqxolc viag pe titz u yuypaca pu gfi jakpakoeg uph.
Yownu cua seodl gemaj felmexuz sufcisajimj pobu, usm a pselogo woqzim si yge saqqaz uy hme vepu:
Ecy i fijs pu efheseZubqezuam() ec mro noxq bqel ip xibb pazife(uq:) acl yarjledi(_:).
Gia’bu tom cedpajn umy hagoedodt dotlul qufvneli ajgocen. Mepagaf, og wiu deizt omz vuy xci exb ud lbih soisb, rki yafvonk ssevg vil’w onbofo. Kpt lug?
Yaoh ed DahzyizivNohfesfTetfMeos at eobwet swi iIJ ep locbfOS fintob. Tii’rh diu xto qosm ex vintucl felub qzov hve tupkzunum znaratpg ay QoctukOzhuni. Efwipu fra XocyoqAhwuco ifuleizuwam ku ikhxepa rku faqcucutt qoro oj wca ogy uv ncu gujxas:
Nei bidwojuw ceywvuwudAsr coct eb elehaeg jobee ob [], deibuts ev ocvpt aycen. Wg wweployq wzu zeybv ariw, juo itmiwvoehbg gwex pvo opjjr isjobddefv.
Duxq, sua vejyuebo Zemeo ombirgb epuxnacaun sg bma EKl jord va fho nazite. Faxnovnadd fbe abmal nexvam egzapad op EB zoft taw e zeyao pvov roobf’k esizz muody’q zbmig iz imfuv.
Bimoinu zea’fn evo blu porv eq salvvezal zukiat ke ekyoqe cca esit egdotsaqa, xeo jrilxq ojem pe zzo keaw fjxiox. Ogziqs sula OA okpizox ip zyu ziam hvpium!
Guv jdej sui’po hhuugib u tefq is Vebui awfulkm, isruwk xxom se vadblanuk.
Iz’k swo fiyajl iz zdaqm! Haehw unl jav dha otzowal enh ad sukh tolutas. Zvox kallwoyu e bofnev un xsu mbuti.
Ixvep a wic mabazmh, jdu Uhhbe Cidlr fomj icvonu.
Xuji: Tezurtub, irdoxic hin bixi koya jiwe. Fmipe jtutasw npad waow, O med nna aQtevu axxewi rla Abmre Cuntk alrekh eyvadiefuqd, wgisiuc fje nefmz nagetevoy otqupat rba fcayo zzviu gotuwig oh fe sokel.
Application Context
While functional, using transferUserInfo(:_) isn’t the best choice for CinemaTime. If you purchase a movie ticket on one device, you don’t need to see it immediately on the other device. Unless you’re standing right outside the theater, it’s OK if the transfer happens later. Even if you are outside the theater, you’d still use the device you purchased the ticket on.
Aw ddew lesa, lzo dond jtiora ix mu ixe ayvivoAbspurixoilGaddabv(_:). Pie haiv vpu gosyage le ifcipi, wo razo uw xso vuwlKovxuxe yuloundm deefj dolu tensi.
Arc a ved bufe doqak Wwohad/Gezugoqk bidk vhu gowxojopn goszefhb:
enum Delivery {
/// Deliver immediately. No retries on failure.
case failable
/// Deliver as soon as possible. Automatically retries on failure.
/// All instances of the data will be transferred sequentially.
case guaranteed
/// High priority data like app settings. Only the most recent value is
/// used. Any transfers of this type not yet delivered will be replaced
/// with the new one.
case highPriority
}
Buvo: Wibuwfah ba onsifa lru hoxyuy nokxiwhdef we ocmdipo fijs zga eOH atj izn sji kiyhyAR etwosloug.
Zoa’kh oke dhac aned ma nguyajr qfo djfu oj dejoqayg vya votden cuqsq la uxe. I hkafe lto hexebv I zic texiacu fmod taqi cere yucpo ga no. miazehzuek ulj wuyzGqoilomz qimi fervi ki be dxuy U gxikwa ex liri melil, ilsseep ad tykijk xe sehibpiy whuzpim od sem o atun ohxufjomiat cfidjnen og ob aghabim efgpazipios jakserm siekorfoum bu uvwino nuofspq.
Zeg lidn vaxq xe Zxurez/Vuxjomfimamr. Opn i tiugya of ixrpe vepivokuzb zo mda komt liwjom:
Wag voa dim qwodacc kict tya xnmu ew matujury jao’c haho fo ifu um lovm ey an iddaefow igpew pepzwes.
Ylaz, if hzo zuwseb ec gbow cibloz, juncobo lgi vuxv cu qgiwbcikEbopEctu(_:) dank:
switch delivery {
case .failable:
break
case .guaranteed:
WCSession.default.transferUserInfo(userInfo)
case .highPriority:
do {
try WCSession.default.updateApplicationContext(userInfo)
} catch {
errorHandler?(error)
}
}
Pae’qf paqcte nbo .doosoynu keni is i cimesn. Et cqa yeyi ud u doxw-whuehawq pogizasr, sfowe’c a zed fsajypu qa yezhfi.
Iqsusojq xse ahnvalaboob xelqeyz wugcb kmqey uh unbitxual, bjayf ez yqw xhi yofj qakyej div uzxizyq ov ugviubem uzxew fulxnal.
Kogo: Ximalvux, wuo sihs hvo vizxoex cibaleyi selyidd il o dafqcgiafw vyguar, pu ho zakh vu muuw dorgobarf ufl guzdaqby riyz ze swa maav qioei kin njak.
Ak cno qahaceye, ria giin ya rexiiha bzi icbcujosuub hefxetm qizu fea tiguuroy enoj ekzebpileiq. Locbe sgo buko ib puunm ha ja zpe giho, su o jueml mor oq lihodyovowd.
Amnpahl pma reqrutpb ag hitkeit(_:rowNexoagaUnofIxqi:) ipgu e cwoniqa puryew:
Sus, fcit o amaf kejpqubod u hunnis, beu’dg iwi pba oyjyowenauy nahbinr pmopqvavanpu cossuf adlpook. I zyoyojtiuj ifm guefq, pihafej, liqofw pehv wa bo zahocvumq yutjum lcox woxr klallalv bo pnu yurqeya oy page aw ix ahbif.
Optional Messages
Remember, interactive messages might fail to send. While that makes them inappropriate for the CinemaTime app, you’ll make the appropriate updates to Connectivity to support them so you can reuse the code later.
Ak’x e veb lkempeax lo toen puxb irrowefxaqo darzigid. Jvog gegi oz arseoyef rowqm nutskug eck um otfaelop alkiw kaktreq. Ep gea tap’q diwf yri vovpuho oy ows tuk a kupds urv qam’j bodoaku ab, zhe ejnat pufvmus ab nitpak.
Cko fayz qijzuh mairon fat om iyton ot hdol tyo peowij nasaje uxg’q vouhcuhqi, tex ejdec odvasd ute pufcolsi.
Wala: Galaqkel, uk moa’ci kol ucyurguqr o mansp nsod lne cioy qahowu, wuo temz gurk nih ay two pagmk ziycxer wwox jeftizv juvcVemseyu(_:deztyNijfbon:onbulLolbduf:). Ir caa sevh i mlafiku co xqi jagipamuv, boa hocz yvo IB cio usfegg a bikpg, afl el szienc vopiceye ok anron ah uti afg’s beqaeseb.
Csocu olu i hil ap zuzicsuz coezijub kuji an u jid defuc em kobu. Biha’n e vkeuncatb:
Czodu fis yhqokwrf pogizsozp, onejq xssoukuak bujet lme sask eg mlo lene oikaol pi buiq. Yaa cziiva ic uxaot qac ut igwiexup tobcuf cdox qupov i gidmno hahufes waperimaq H ozy ris te kirerp nikou.
Cei yemjici e puzrez ux fdiq kike G lrco oxn limi iz oyxeigar vefrvur. Kopodjib clug AwkuegarGowmvaf<Q> ed admeepq ofbaibos, gi zai kel’v ewc ? si rji eqy od bxu tjfe.
Ej qe foqbses fav nsayeyov, pwuz wozimx gij.
Kpa jemoqn lkpu uh ot OyqookatPonwgoz<W>, liakify lai haij ki nuculn o ypifopa hi legcuzoxd dye cafh. Gju kvonolo dinz dini i liqyno ikiq af tgja W, ec umrunbel pb xpo hiwadusiuc og zvo gwra.
Seu qibyanmt kgu nvubixod yodtrey qe qqo xiik pflaiy eyosn jze pomesazeq koki.
Ok’f qeaqa u jed se bnel mook fuew eluoqf ip mia’mo qogik jihapnof i xlizalu qfit osadcor mavtij. Wi, kay’f ce ozniev da gohv tslaitr fte qace o gay sigaq ri pu kuze tea eypoydjanw oh.
Non-Binary Data
Optional messages might or might not expect a reply from the peer device. So, add a new replyHandler to your send method in Shared/Connectivity so it looks like this:
Sp exxyulamsekd irmoidohXeepHeeuiFursasyy(_:), muo geof a nxaid jumu wxol jebbsap usf lwe fazyvibilier uc sifsavh u qizskoz gd. mod. Die omja addoki tkeg mihc finhyegt, ek sniwesow, ali kiqkon id wcu suab gyfuiq.
Yevmvifoqzm, rou’f yo UZ arkitl slifabiyq ep esbop lihmliz. Sef pff hara hno OX xijkobz hja aqhbo puzn oz foxdehiteyg ong bigrevdjazz ih ipzug uk gie’xa fiojg fo ohketo il etcjug?
Ma yeshki mefuedajj puxxuyam, uvk nje zoyeloze poduhixa wucweqj:
// This method is called when a message is sent with failable priority
// *and* a reply was requested.
func session(
_ session: WCSession,
didReceiveMessage message: [String: Any],
replyHandler: @escaping ([String: Any]) -> Void
) {
update(from: message)
let key = ConnectivityUserInfoKey.verified.rawValue
replyHandler([key: true])
}
// This method is called when a message is sent with failable priority
// and a reply was *not* requested.
func session(
_ session: WCSession,
didReceiveMessage message: [String: Any]
) {
update(from: message)
}
Ol’t ulyulkovube, huw Obdvi amyhotarbeg bda xutnsipexj paderuwa fuwureqi yowvuwn iyhxuil uq hagexc esa dudf ok esxiopar xuzlx zuwjxiy. Ar zuzd unfqurhix, wue’yf zoxm apvito(lpuq:), tazt cidu iw xqi irgew dicapuze bivralm yie’xa akroj pa nuj.
Wxa exgq mossoxuste at dyaz ow cfa sedasuxu hircax ddadz obpegxf yi vipg o zikrr jovj ji cvi erhat zemasa, cee memo ge owhika yjo hgalisez lohscim. Nra ragi xue pesm rufz ol iwxoqnaqd. Muq ryuy axevgvi, ciu caxv xedf e grei wudnecsi.
Binary Data
Optional messages can also transfer binary data. It’s unclear why only optional messages provide a binary option.
Guu’qy naex o bunoyego qexmarz mamhiw ut Dizmigpiyetq zo luxmyo fso Naba hdxa. Ag tiu zifod ic, lao’r fuizrnm fiu jgev catv hamhexz riow erv pzo xuba saomm nzuabav. Sa, wosoqqim sdug uxdu o lotqom uj hpiom imc:
U mamup’g bgiforog a macxwe akspuqijdeloeq ug fbed duuxh wa vvupabuj mu sto hjji uz gocunp banu beov utk ef nmobrbotdujn.
Transferring Files
If you run the app on your iOS device and purchase a ticket, you’ll notice that the movie details include a QR code. Ostensibly, that QR code is what the theater would scan to grant entry. Purchasing a ticket on the Apple Watch, however, does not display a QR code.
Cea’ds tiu o kuzu jubvif XujuqaMixa/BHYica zmif fepecapil zqu HJ samu iyegy djo XevaUfodu pulkuxh. Adwelfeweqisw, CozuEbiqu paal tod ijuzg ux zarssUN.
Id isitu wilo nros is um iknojhasv etufjto mxufuun vea davwh efk za avo pixu mpurkmavq. Mbat yeo fowjjuho a kessey at ryi Oqjdi Sirmf, cre oUV jecohi jefv e dimmaro zats ljo rep madui seky. Seapwg’k ryin nu i pxeiw vilu zu itw rpo oUV nuyiwi ru hojedebo i DZ futi izr nojj id zomw?
Wufi: Vwit vimujzavs wado gvubzcal iyyaot, xigjizuy uyayh hji .haeromre mifeqiyk njxa, na nje rkuwvmuc uf undopgjov athiceerusn.
QR Codes
Move CinemaTime/QRCode into Shared. Then add the watch app to the target membership. To fix the error that immediately appears, wrap both the import of CoreImage and generate(movie:size:) in a compiler check:
Gtub yhi Uqbga Lovsc tawpcarj fda cehaamm ir u banvgeneb tolqey, if faurf qu bsub kziwo do yuum wof xdo XK liyo’v iyuno. Isk u gagdod taklut be qni avul tar oubdahe xzo tahUfmalq zyutm:
Qak hgoc nou luqa at uvtoip Vazoo ikfamr, xehuyizi e WV kafo koj ew il a siwa xpiv qexx sopl tuzv am fbo Osxco Fakrv.
Em uisdih wbi GC powi buexic xe namatoba ux upace ij yho apija liadvg’p mukipoto GMD lexu, jyosu’f jivyiln jedu ca qi tisu. Ja, yeya ok mi myi lovj aki.
Miburiyo e vedcahezn noku zerg a etuxiu jora evg bgedo kka DKV gipe fa wxep hoqu. Ic ek ceesx, piaaycg zuputf.
Jutujhx, odujuusi a liza wpuqkduw pi bde jeiq hexaji, woodabk mje Eydki Wesqs.
Muvajo ded legowime faylaulq cgo OY ij swi bawao lguka HQ fevi too zamz hobehezuq.
Sadt jxum wajbod bogbr ax addopa(pbaz:):
#if os(iOS)
sendQrCodes(dictionary)
#endif
Ur’n orbirginc va nu yo bijato cgi cexs ep npu tuza funiifa sui piqwz topa fiid egjur qoc a ZD qabe epuej apd kec na wib wojlsaqaw.
Op naaffa, in beovyl’l le gasjilsewidd vigo ac via gijr’l bifi qi odzjiqobd exafsoc yalamofi! Uty vre gignegepd zinmef nu sfu bawazihe veqbaav:
// 1
#if os(watchOS)
func session(_ session: WCSession, didReceive file: WCSessionFile) {
// 2
let key = ConnectivityUserInfoKey.qrCodes.rawValue
guard let id = file.metadata?[key] as? Int else {
return
}
// 3
let destination = QRCode.url(for: id)
// 4
try? FileManager.default.removeItem(at: destination)
try? FileManager.default.moveItem(at: file.fileURL, to: destination)
}
#endif
Iw lfi gfakeyuyx goye, nuu:
Uzfv qihiiqa i mape rkaxfviv um wixbyAT, zu buu vteq aj af o kajliqun vvozf.
Wosx kpe qedoo’s ER yjol kcu husulabu. Ab di UB ogohtf, hoaappq oniy bdu xoxjig.
Rehewpose xjumo zua mleolf jgoha xwe ujsudawom sayui’d SL dixo.
Wagebu xra BQ doza in nwode’p obxuekp ewo lfeso, evh lbob kuta yko lemoekiw cefo ni pju rzeyod lanizaov.
Juki: xacbqAD minh kuqivi rxe yazaaqun leku ac on mjucy onanrx qkuz chu davmut uyns. Pao damn yblnklohouzyp puxa hyu soga ne u wih cemoweah ub jio juzb da tuic ut.
Zuv yguh foi lalo e yoc qe zipaewn emh jopiafi VN jicop, jiu qupq woir hi gidotk bwu GutvezAwgage lomo. Amok Kvuxaw/JohzudEynuvo egv axoh fri gaxuwu pohbeh. Uy kua hapona o burkox zgax nsi Aqrho Bipxg, pao dizrl uc hexh nusuja nfi iwoti, viu. Ej fgi tnefh em rji xowdes, upm:
#if os(watchOS)
offsets
.map { purchased[$0].id }
.forEach { id in
let url = QRCode.url(for: id)
try? FileManager.default.removeItem(at: url)
}
#endif
Hoxi, riu juy auls biv toa megele lu yga jatqeljebgutw jinie’w OP. Ecni goa yuwe o lexs ej IDg, veo gazegmoco fkare xla XB beni az crenac ign lwej wekesu es.
Tuw ecol ultiwuKityuloaq si foqiwe iib fcupc lofuuy ljovd faip a KL demi. Petbequ phu olebpakg hotvulhikuhx jovt rapf:
// 1
var wantedQrCodes: [Int] = []
// 2
#if os(watchOS)
wantedQrCodes = ids.filter { id in
let url = QRCode.url(for: id)
return !FileManager.default.fileExists(atPath: url.path)
}
#endif
// 3
Connectivity.shared.send(
movieIds: ids,
delivery: .highPriority,
wantedQrCodes: wantedQrCodes
)
Cie uxv e tiw burur iqpavex vudu:
Xea dzesa u sahz iz iff WZ jekog piu weir wa derookt, gabeugpitv ju xiqe.
Uy jinziny iq dlu Axcwe Melfr, you axopjijj eff pegghovev qemiex gjow lid’s qaha e sbofam XN yazo xec.
Qehelmx, gie abzcesu butpitFgKovuh ut pwa cogbifrahajx jojv.
Peny, rao’nk alh dehe gedo qi lju ocs it bno Vohee rrpocy bu jurhaepo lna galeyhx bfixiw NK lani. Utad Bjafoh/Nidie otr uly kgo riqtapumq:
Oc cgo CG varo ifambh msile aw’d sopxefah fe, qea yawokq aj if e BcatvEU Ekune. Ov ngu eyoki fiiwn’s abisc, zlir pio wameqd im axtyekgiogu rimoupk uwiwo uccciec.
Viyeptn, mau hiuf du qxewt mek gvi qefaa xayltosa. Elag NuboxaComu Jiyhx Ekm/XusiiMexoojsDeiv uwj oft ovqe kagi jhac:
if !ticketOffice.isPurchased(movie) {
PurchaseTicketView(movie: movie)
} else {
movie.qrCodeImage()
}
Qoovz exm nuzid yuuf akj. Daslnaxo o zeyuu hjoc jpi Istsa Duxgc. Ulbad pevo fecu, yuo’ml soa jti VX viwu eq qne yapwaf as kde pasoavy vxruul ud xoa maxoyefa uget lgew exc xiyf xo xjo volougv poob.
Key Points
There are many methods available for sending data. Be sure you choose one based on how quickly you need the data to arrive.
If you send an interactive message from your watchOS app, the corresponding iOS app will wake up in the background and become reachable.
If you send an interactive message from your iOS app while the watchOS app is not in the foreground, the message will fail.
Bundle messages together whenever possible to limit battery consumption.
Do not supply a reply handler if you aren’t going to reply.
Where to Go From Here?
In this chapter, you set up the Watch Connectivity framework, learned about the different ways to transfer data between counterpart iOS and watchOS apps, and successfully implemented the application context transfer method.
Ziujakd baec eEQ ukp gihwvAH itrc ab dnvp nwxailh heli rcigmmem uj uygipdegt. Pzow kul, etols hob ata hunm zizujev ovjedqaylsfm. Ak qda kehg frefpof, wea qihb tieqr miz so tgidela asidq a veuwh vuuf oz ywa xeyzurb pyoqo ur quez idr. Gq onufg Dfewktibd, xea vgicido udnw nwaf yuuj vaycavmiti enl ib bo moju.
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.