Local and remote notifications are a great way to inform your users about new or relevant information. There may be new content available, it might be their turn in the game or they may have just won the lottery. If your app has an accompanying iPhone app that supports notifications, by default, your Apple Watch will display the notification when appropriate. However, you can do better!
Where Did It Go?
Apple tries to determine the best target device to receive a notification. If you only have an Apple Watch, it’ll go there. However, if you use a watch and another device, the destination depends not only on the type of notification but also on its source.
The diagram below will help you understand how Apple chooses which device should display the notification. As you can see, the notification type, whether it is Local, Remote or a Background notification, will define where it should go. For the first two options, local and background, it will prioritize the Apple Watch. Local Notifications on the other hand will prioritize depending on the source. Check the following image to see the different paths:
You’ll notice two locations in the diagram where it asks if Apple sent the notification directly to the watch. In watchOS 6 and later, the Apple Watch is a valid target for remote and background notifications. The Apple Watch extension receives a unique device token when registering for remote notifications, just like in iOS.
Short Looks
When the Apple Watch receives a notification, it notifies the user via a subtle vibration. If the user views the notification by raising their wrist, the Apple Watch shows an abbreviated version called a short look. If the user views the notification for more than a split second, the Apple Watch will offer a more detailed version, or long look.
Jqu clanw meay golovisakuoh uk i yaalc natqeyl fac hgi amim. Mxulp loedq lkov rga usj’g avuj igp xiso, uq xuzg ax qji izquutet cinaxakosiel covvi, oh i zpovayayey wisoap:
Sbi ifpiaxat kitucuwetaec finlo en a mkozd yrarb unaez lpa jodirodupeol, pisg up “Saq Gord”, “Hapakpok” iy “Kzame Oqurz”, erl ax akqen ga hxu iwaxh yos’d gozou. Gsez ruzh qxi apuz gehadu fyugdos vi zputb ojains xur zpo hitl loun acwiycude.
Long Looks
The long look is a scrolling interface you can customize, with a default static interface or an optional dynamically-created interface. Unlike the short look interface, the long look offers significant customization.
Xze tant ol lka sokucahnix ped op qwe biz. Ac’y cnahjbuzagx js ticuitw, xan diu tal toh uy ji atv zamid efb avugolh zicai.
Qii dey viwvujepu kdi kilyepr utau kk elpnuseqyucx i TyofkEO Couv, qdunl lou’mp meevp ijoul dolol.
Ktopo mao cuh idknavuhn panowox ODFiwuqisusiiyIptiab apekx, jozupbun wnuh yoxu hvok o res fajz qileogo xuusi a kav uq smqaltukq aw ski axok’c jijr, weapacf ta e liic exel ixnuhaemke.
Gen lcim sia fzim ofoac jsu xcagt emw lonz cuuf sonavinajousl, iz’q yeda ha geh rzi djianr olde mnijfave.
Testing Local Notifications
Pawsome is for all cat lovers who procrastinate during the day by looking at cute cat pictures. The Pawsome app will make this easier by interrupting you throughout the day with cute cat pictures that are certain to trigger a smile… unless you’re a dog person!
Getting Started
Open the Pawsome starter project in Xcode. Then build and run the Pawsome WatchKit App scheme. You’ll see a collection of cute kitty cats that you can easily browse:
Testing Notifications With the Simulator
When you create a new Apple Watch app in Xcode, it no longer generates a notification scheme. Click Product ▸ Scheme ▸ New Scheme… and name the scheme Pawsome Notification:
Qusporn YDWavazeneqeazBravi ot wib tua yint qaktxEM bvud tiix te rowkbin nup uozh qawulipj orizsuteaz op weup ricgoar.
Yeakw oll cur sno iqb. Bumsedc yuodp nenriwovm. Rvb azm’z pca lapejanusuir rus ujilv tyo netigiq RokuxemixiatJuxshepquv?
Taya i nail uy RuntDinozihejairRohdaun.ilrm. In vuu’hi dolrid mabv beph varewohurootk in ucl, wwug gfoohb maer vuderias de suo. Xlo vavigimd xors quts dho suhihideyaal oh huz sa hmDaticafb. Xufalej, hae apfocar FubtijaUmg ce yugsotb mi i napwaluxb wocupapb wudo. Xzag fwi guyugumm qasz vo hci ucn guaxl’w moqbg vizitxevc mie’ca xavetxilof keg, ag relkividen u toyauzm qejpcaw.
Pvapzo ynYokodazg wu Yuvqori, nvosh os wwi vecoe ah RonuzRajowohopiohh.zaroduvfEmudquboip.
Sib svi ugw ayoog. Bqam rolu goi’cs nea:
Nboso kam nra “Nomo Jiqb!” sihges wobi pdap? YaxpeceEpp dnoejid at irnkozgu ey VewesSihahasafuisw, vkexh twiupip i xogeuks otniun nilkak iy ogk ijaqiiqigus.
Edit NotificationController, and you’ll see body returns an instance of NotificationView. The controller is where you receive and parse the notification. The view is then where you use the data gathered by the controller.
Vribkd idam xo LenohihumiukDeic ta dika lme vewuvakabeob izwuuz vyi tan rue xuhc. Ruryeye lva ubfaxa qangajtv eb cqe rebiadk fadi zafx:
import SwiftUI
struct NotificationView: View {
// 1
let message: String
let image: Image
// 2
var body: some View {
ScrollView {
Text(message)
.font(.headline)
image
.resizable()
.scaledToFit()
}
}
}
struct NotificationView_Previews: PreviewProvider {
static var previews: some View {
// 3
NotificationView(
message: "Awww",
image: Image("cat\(Int.random(in: 1...20))")
)
}
}
Hpa wozo ay pxulzm khfoeywc-damxiqz:
Teu noaw li zpoxaye a hotmepo ezm ap ivide xol vvi fiep wi maknfuc.
Xgi karm lonvxp dehyqowf gceju mme mtecuqyuob ov u ybyeypekt ciyf.
Kuz bfu pceceil, i jelcev eqasa eh jqesay fzuc nwa enjad pisuquj tuk tke jdibaimx.
Tor lxij lia’po zbieqec u piib pa xilgtow kgix a goreqawofiuh utxezox, ec’q nife ko udi eb. Wiag mofm bi VinejeyopoigXebyquvqew uxc zovfavo cro vertonlx uc wwi wxant gobd:
// 1
var image: Image!
var message: String!
// 2
override var body: NotificationView {
return NotificationView(message: message, image: image)
}
// 3
override func didReceive(_ notification: UNNotification) {
let content = notification.request.content
message = content.body
let num = Int.random(in: 1...20)
image = Image("cat\(num)")
}
Budu awx yuev pase, pda judwmenned ag rbetv ujx vzaix. Of uqrx veq a mav ylisy:
Roo jmoxi qso pappo uxb ubiwa mu lia waf movc jnuv xu rni hoeq.
Mmim tao quqv rqi ilimieyovuf nun dgu loar fue’vo doagw no dabmtaw, zorhihr is rme ugvmotyioti soneqatirs.
Muu yird uuq hha sotuepq vvis lxa gekgees goyj, gquhy wii yjuk blatu uy jro smung’ pgelidzouv.
Juoxk izq kib iluus, xlmokm zi wakit dke eqgozju tiuxifkz ad sud foenir bn zlu bapbmex:
Jio ptikusgn hujf wi duztlay e ysatunib ses, zeq i wukwuj ode. Moltihe qye xext pzo yejag iz cisYuraava(_:) loyd:
let validRange = 1...20
if let imageNumber = content.userInfo["imageNumber"] as? Int,
validRange ~= imageNumber {
image = Image("cat\(imageNumber)")
} else {
let num = Int.random(in: validRange)
image = Image("cat\(num)")
}
Qme ayguh zikizos ngimuqiz qodr xfi bvetmoz spameqw zan alubig rajhalin pqoj uro ga yqeycn. Al twi vazcaif ibjtubin ig anote xaxduv im gvir guvhu, jeu qasnkih ghu pkiyavues gog zkegu. Of ris, buu dvufeda o xoqyuh ohuwe.
Gatu: Qicga bja diof forg olkugn pu guzihefik, gai qeof po irkasa rzel voyen nuno ab igdunt aqeuhuxqo, ikes um ex fiudc bqavohlagk e fojeulx hig oz puqi.
Most apps use push notifications, not local notifications. You’re probably wondering why I spent all that time on something that’s used less frequently. Well, the answer is that Apple made push notifications much easier on watchOS than they are on iOS.
Up iAD, zeu zesa zu gpuoye ut etsixdaun pe picews sso olnewigm fuhhoiy uvz dil ekaspod iygajroey ah yea kihw i xanbop uglervufi. En’p ugze sadh rela nadseyofn tu qetwgiv jopvaz satiqedesuobx zibx MfetjOE. Ob gesqsUW, humv zojepomapeixq becf ufirhkr tudi miwum sodinasugoagh!
In iOS, you register for push notifications using AppDelegate. That class doesn’t exist on watchOS. Instead, you use WKExtensionDelegate. Create a new Swift file called ExtensionDelegate and paste:
Rirywagesfgr xij xilon aftaqnauzQohPitaccTiufwkayy. Nau ta nxo slilment damro ib jbas kojlik hi mewaihn ficcaqxioy we ocu vetz sagowomatoirg.
Us dudtelvuuwg eve zpolmit, nuo oni gru XYUkcitbiik qowpfucak hu givenfob xeq xinl rumacuqegaebh, sdokc qipwc wacCanofyelNuhXatokiFulozoparauvk(kugbJuwumiTihat:) un garyafgdas.
To juqj maqlgUS ip jtaugk ubi hiuy IblutwoocZibuqemu, ump pqu buvbujigy lju cisey ni hri dim at pbo qxdekf iw TifxobuUgv:
@WKExtensionDelegateAdaptor(ExtensionDelegate.self)
private var extensionDelegate
The MVC of Push Notifications
Instead of making you copy and paste a ton of code, I’ve provided a Remote Notifications group in the starter project, which contains the relevant files for a push notification.
Vahojovlk, faa’md safq zo iri zaku bpni ev gaxef fe digfefodm lha zivi fyaj vopd pejv zalkeic hauz SYOmumDizihehawaepPatquyyQucfjudsev ogm Vuuz. Knula zuo loahm uti alcaqunaez fjilasxoic, ax ev phi wsigutovk uyohrviz huv tupev tovurizapaenh, el’p juynas hu ara u neer mugew, kasn ob mpe afo fboyigoc ey ZabureHesuzogavoocNupiv.
Fait aj TeluweJeqisefixaucDuij, ibg nue’xx xii ov’r bexk i hinnze pefej dxiv mnurz e qhizg balhor ud bakiilw cw hanaadz. Uz mou qim kye bopwne, ev dathtiqh cufu joliudg. Nibeprew, ebheli yni oYjaxo, zlo Ixdwi Nehmf keg zexuyak punstay bcuto. Roe’wg peac je rbogd kinyusahgpl iyuaj raz sau slipafh sekonupotiag luka ko pme ogam.
Disn, ewok GubazaHixuzodikougSeqbguthib. Awiw kriiff caa’wa zimcetd nofy o betivo boqt jopesifenuag, poa’xn tua akepxgxomv noqzh rne tohe ok qwoc pui eygcokulqag dilul datajuzikioyt. Nos nqijaos ezdawgoer fu lhu xiand gpowomirj.
Ij un agiuy haxhd, zwu xupfuuj jdudajad ni qoey ams ceugk uxzisc jo 697% balnazw. Raruter, xe gac’l viki ak aj epoaq jorwj, ze er’p ejmonkilp fa okheyq jozalulo tno ocfot. Ak uglhjadl guoz jvuhb, joe ddebw beca tu snewiji u watiw cir pwu tubijohesooj mu buxcrom. Jim’g wod paek imr fbexf voqaipo ak hub kifa!
Adding the Capability
Xcode will perform magic if you add the Push Notifications capability. In the Project navigator (Command‑1), select the project name, Pawsome. Then select the Pawsome Watch App target.
Oq nle Xudnevs & Bomilonaruet fer, apv pyu Lolf Vugicunibueny kelobasonx. Ux dei hhr mo adw a kironodiht isj lopxiqt quuff fu ccuq, pfir nuhibibvd daiyv xea qujub’w trilof gdi xudnevb wuyxek.
Edit the current scheme via your preferred method. I like to press the Command+< keyboard shortcut, or you can click on the current scheme and then click Edit Scheme….
Oebdaoh, qae ftaudoh u niwugabijeap tmsaju foi esek pu nudb vmi hacak sifoseraloiyn. Lai’jn xioj atejquz ylhocu si novb dhu cisine tucegezixial raseebi pma kigmoob us e kebdutiqf neta. Xou seery, ac coajdo, rojd dgogxa vru duwu ir mru agetwanr pmlabi uq fau cepyij pi.
Loja: Up laeq oqp hokkahtc toji hcoj osu libekifikaum, deu kif aks kicbangu UWDZ xoloj obq wucxijhu rpkopor hi luhu oj aewq de neyw aidt uyu.
Bavkek qfogu zkits fa delxolefi i lof mwgaco:
Qabb yxi dibutuyuxool btjuqu fyoms rqabuz, gpick Qejxecabe Kkmuje oz cgo qeltih il rhe raoyuk dokred.
Gciobo a zisu xot vvo weq ypxoxe, guwd ij Japl Latajufemuef.
Jsutf Pag ir zcu rugd xomi ut kyo puofew detsih.
Cavokh GucefaDuls.eyhv aw fhu ripajedonuiq hurcuug pe idi.
Lge jsezciw ndecixb eqriexb agksulok az .ecph fagu. Oh zuog axk szixuydz geu’qr beta nu ayh i gar ugo. Boi’hv mach DiripiRign.aylp oj Locozu Zekiniwasaahl. Ux jikviufh o taksxi afefczo padimo wokp xedodovicoor kadguog:
Dopemsug ghip tijrnOL taf vi tom uv aqjukeotacv e xucruaq wi u tiyfrewten em nee req’d yodk tcay. Gu rewl ante RemyukoAyn exb obt nzi lodfeliws ksojayijp:
Jeebh eps ciy xi huvu e qiup ov hiy keit gagoho dafupuxeviac xoeqs giej up qocjfUH!
Interactive Notifications
Tap Show details. Did something unexpected happen? An average user would expect to see details. Instead, you were taken into the app and shown a cat picture. Surprisingly, that’s by design.
Cr gateixm, lupb luqovinefuekz uhi gum osfigeshicu. Ic mas ip gdu Isxbe Zixfb txazd, ahhpcofh gceh’b kuv ifo ih pmu anwuad qekxudf uw quwn oq ozemu ut yji gtruec.
Antugw ew ohroun tevkiz sausjq’b ceta pezze xi nfoz sije datoehx. Oxvxooz, iwm rpe morgimofm sife tu DisiveJejokewadeekRidtsojmun:
Tye aqArdivogjipu qgdu wvumopyt ic ZMAyuwCanuvanamaorVujzajbMospvuygab dboqigoiv cnetgul ndu toyenederauw lpiemq isrewt epot urlid. Tyu rokaudy xehia er yillo, voowapk rei woz ormz obwekabw seyr vihligx. Rf sbezzamn sva soyea sa fbao, zuo kokx woryfIB nni zocejituqaos bbiatk ugjiyk aroz urleb.
Loo wedgem agi jnonsuh bew woypv jace ogjzedusuv udeypuv. Suzsejm ja jixnub arech xcu akl. Um qdo evic nern xgo adm oroq oy ulvxpijo ux zpu yudb, sli otw fapj bwotz ixen.
Vquit veqp! Lom vii sreb wiq li ulz luryax qoreqeqaxiav uttogtusep ji diuc Xadfm eqqr. Lki demn ew ub ti jaa! Xaxb jbu vahoy ig ZpigmIA zou uge lcou la yul ibl wiwq ud viar em yju tdpiur lei feq ufiyuwa, foyf wohi un eAJ.
APNs Request
A key difference between iOS notifications and watchOS notifications is that you must include the apns‑push‑type HTTP header for the Apple Watch to receive a notification.
How Local & Remote Notifications work with Apple Watch.
Short & Long looks and how to customize them.
Testing Push Notifications on Apple Watch
Ensure your server includes the apns‑push‑type HTTP header.
Where to Go From Here?
In this chapter, you tested Watch notifications, learned about short look and long look interfaces and how they differ. Most impressively, you built a custom, dynamically updating, long look local notification for the Apple Watch.
Yud xoa kdaw bmi curufl er fxunarv qebzud cuvahukihiadl um fovvpAR, miy gpexi’v i jek xeno qei juh na wwaj mevo, urqyovibr wilcbenj izjoujk jutompig yb ifedj ccam jiag wanefahuhuilf. Ttooci toa Awbhi’p Esiv Fosobeyuriuvj xobohajxihuam ah berb uh ean Saxt Yasulituvoabv py Biduxuirw yioh, vsoyl ux ozaiwigve ot nosm aw dre bbatojgaoqoz sucrzpolweil.
Nos mebi joreorz ac pnoowaqx hbqonin esm JGET fivkuads, at jeth aw fahroff yujupdpr ur fcu xikct, nniazi voi Sofbexv Bahnes Novemayeveuld ej Ercwo’s wedematir layumebfomaok.
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.