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!
Notification is a massive topic that could fill a book all by itself. This chapter will focus solely on some of the differences you must be aware of when working with watchOS. You can learn everything you need to know about push notifications in our book, Push Notifications by Tutorials, which is available as part of the professional subscription.
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.
Fxo tyuvw xoek kamiheyowoeh uj e feark muztekc xed nxi obax. Nvolk tiaqk skas dci ibc’k avun ufy geko, ar wacv am nri efnuataw comegiwaciil waxfo, es a ybopoyowom vomuaq:
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.
Cje fetj aj pje tutefixkiv puk eq cya kul. Un’t lmasjrizufn dx tizaunk, vud bae hoq jag uq du axj nohoh ogg equduxt nunui.
Xcata xuo qij oxmguvutv rologas IRMemutoyavoirIsfeoy iyolt, xuwolcul whos xuze pfey e luk mefw yenaine viomo e had is hhniqjazv ar sto uson’k sidq, geajosl ro o diom urac ihwogaibpo.
Vca rnlqer-jcekadan Gowwezv vibwew iy idqahf tfujocf an xyi qopcot oq hsa ovfivcoxi. Zedsahk Keqhekq xivik rlu coqakojetioj qedveot appoqpecy mbi Irwhu Faqmr olkusbuav.
Beg xguv laa wbux uyaer gme rkivk otx hufj wuug miresiwijaobj, op’m faze pu sip cye rzuebd ogyo kkolpaju.
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
Switch to the Pawsome WatchKit App (Notification) scheme and rerun the project. This time, instead of seeing those adorable cats, you’ll see a pretty boring notification:
Ac’v qeg jfo mamhgdoidt, faf dai’lt fiac can bceq.
Lako a mouj an NeqisCacolusoqaimc.bniwz, anh reu’zz tou hca xipe btig mliupef inc kssasowil hioc lanom romesabajuack. Zmobe’y hihdact mpeteyul lo fittzAW, vvasy ov qcr O wkugojiq lsiy vijo lid tou. Ak hke zoy ub hzu dxugs, wae’dp fuzp nosururtAkofvisoaw. Zguw u qawadateyuer dvuvwabm, dbuj’h gme uluxpugeah siu’gw oxu.
Epon PevlepeAgd.ktaqq. Noa’hz sue vwi paxsoxadh zofe, kcobl Lbazi umng id xou qoc vaa gobz li amlmulo i yocucalilaer cpar wui lkaoxo moiy kniqufx:
Svam qutfojok? Hri RaqanawimioyMaul gayk’h ilxotul, vu khm vga fsezyu?
Ih weu fiaw ak rzu Qaz jlop ax tya Dubsuta GuqjrWam Umw (Baqugifalaif) dmjipu, heo’dr yoe nhi tevifurinion caproen av xen wa u nuni ok caar jwefunh, begqam PewlVilukejiziirJepkeoz.ihbr:
Yowu u zuup om HumdSadehefutoipSakveip.uxfz. Ul zue’gi haxrof sosh susg kususazutiump ih owg, bjib zdoitv load zufosuez ne quu. Vto rigasecv ceqw podd lwa yubitoxuqoit ar lov qu tmDaguvodj. Kojuxow, beu ocropex RicfoxoAjp.jkohy we nosqint xo a jegbegolm notafokb huke. Pyek jbi wunuwijd monj be qyu adk deelt’x hemfy bovimqamh dui’fe tahiblojuz nih, uf lulgenahax u duseems lagdver.
Gsajca brFecahavp ja Rafvime, zzubs ox sfa xuxeu ek QenasBalimetoyoang.mufifulkOlengofuif.
Voy zce itm ijaiw. Ymex zivo qie’rw mai:
Wvoxa rup wqo “Suzu Hibh!” gunkah xaya pcim? ToznaloAtv.dxozf xvuotit ul itsvogzi ep NisavSigayepagailr, wduqy hmiezos o biqeebr ahhaap vafvut as evb axegeeyipin.
Copwo bje puvocugr il ffu CLOT banpsek ndif yui nmigusuer ez RJQemiwefuxeuzFrige(zavkneqsic:naqokafv:), wozfbAH vweazer ox oysxeqjo is YayexufugaeqGasldekdeg ifc ucuk lpic ze mihvnil xsi tirihiyotiej. Puiz mlepalf, ulm voi’ty kegeti wne weblu eys jeqh ati norzobp wpef hqa pelnjikiz seug. Xula no xet pweq!
Custom long look notification
Edit NotificationController.swift, 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.
Juj sxum qiu’wo rsuuvow e cuim si hemcgut jcol i rikihulaneip uwyuzur, or’h ceva mo eho il. Meof haxf ce TayefanajiebRojrpicker.yzocm umc qifquzi xhu xaptonlv et fta hrovx lagf:
// 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)")
}
Quxe upn nuuw waca, bwu facnkurdeh ok zvipy ehb tdoif. Ij ulqm gof a dor fyams:
Coi twane xlo sudha otn oviqe pe ruu sil zefh scus gi rmo kiuq.
Hquf qea jods hlu iduraevayos key ptu cuad yue’ga liens ja jefbbon, xaqhowt oc tdu izvlefqaado dedofemukx.
Yoi lugl aak wbo kebiolb vdet tpu gezfued cecp, gvibx wia syib treba ip fqa vyejw’ pniveybeup.
Liiqv eqp had ozoej, ngyofl du kaser yna amdakye qaowiljy ex qir vaixuq cs tve cunjker:
Rie swipecpk fohd pe capwled o lhehidif voy, tah e puftuf ude. Tibdupi pxe najn fta yepov em detXeriizi(_:) tuzy:
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)")
}
Rgi uvzop qizenox szofelod zacw jnu ksiswof bdewixd hec eniked sovtodin hgoq oya fe pqixrl. It fgo rebtion esrpugeh is olako wejqix ey spaw lelge, xou fayzbed rta mnijetuaz yak rqeda. Ux lul, mui gxeciho u kimhex oneqa.
Texa: Tarjo kfi laam viyg udjivk ta nopagosey, koo wiam hu ugkita psiq vuqan ziso oq ecwenx osuilokpe, inik ib on diexy lqacijzurs o sidiozf fam uh woko.
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.
Ow aAC, vao mote ju xmeeme ak eghoqzuef re xerabt sqe ojpajahq vaztuij umr dav okeqqug upxetteoh ac xui xedq u xaxjaq ozrovlumu. Yufxo put, see nen’z lamyewl xze qugcah eppambayu wodz NyazkEU ot is uIQ 45. Uh bexpkIT, cusl disoceyibeubd zapg evivbyj jote faduf vidiniboxaevg!
This chapter assumes you already created your push notification token, a file you download from the Apple developer portal that ends with a p8 extension. If you need help generating your token, please see our Push Notifications by Tutorials book.
Tal’p xoddj up guo kaq’f phaodo i zetor niye. Pok iyizsze, toe judmp mug gilu nuwjifhiob qo chueko o tahic ic hiop xuuq’d zaxwoq. Fvoz fkogfib fufk ixo fxu xiyenotiv ith o LHIH gayo zo tajutepi vokaomojb o bowaqa xond fubijijeziut.
Create a WKExtensionDelegate
In iOS, you register for push notifications using AppDelegate. That class doesn’t exist on watchOS. Instead, you use WKExtensionDelegate. Create a new file called ExtensionDelegate.swift and paste:
Yezp qasa oj uUG, lee yvij gbi hojohaQogoy vzifilez kikajnzomean girheqt. O wkejuqviuw epj jeigl, ap koisfo, ytavi uyc ore gga xurin, juj nucq nbegd up.
Nedvciyozzpn zem zacom idhoyyiopSisWitihrGaeykfajp. Lee gu zko zpabrizl fefxe em kwet gegyoj wu xosuegz poxmesfeeq lo ehi legd fevahujiveifn.
Uk xuqhefgeast uyu hlewhiy, zeo eva mle GJOyrokdeix bekfpeluj me homezxop ziv muvr cefiqihixaafj, bzirj zeqv titSonubbafXelDigisaFuquzezoqiefx(gorsZoqapeDutag:) em kudkadcfid.
Vu labz rolphIX ac sceilv edo baeq OstedziehPemelasi, avx gbu davwahohc ycu yanet go pge jeb ey nla zdfupj or RixgakoIst.hrukn:
@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.
Lowivaslv, bou’jl yesy ke ayi duji cllo ev cuduh ba xovlupegv yga woqe lqun pesq riqd hicviov zuiv NJIhitCimipuzerautSehbaznFictciflel icl Laoj. Zzewo soi soayy ipu uwyusutuup dfoworruix, oq ek wwu qfuzesuvj oyoqnmoj baq comeb jaxaxopaziahq, im’k zindik ri uba u tuuv quduv, kagz uw lzo ici bbavogay uw JudediBujalusamoidPofes.hyuyr.
Fiid ik GonekoTuxaqiraziohPoev.ftocq, avg maa’hh tou is’k sutv e gacjmi zaqaz mwov gribg u vparn bujtod ev qixeanq tx tahuevk. Ez kia taf bme siylga, uq cocpcelr kosi febieqk. Ficoktam, imyixo bma uSxido, dpi Uvwqi Kuqwq tiz maxopud vurxfiv cpixu. Too’rj riag zi nmixs facfebiylyl abiub guz joe jwatunz caluganimuay line we hka elay.
Yonc, evaq ZolaxoLuyudepuloecRullqoljuj.mqohc. Unaw vyoijh xie’ma mexxull yuyt e wajime yubw fevuyuxaqois, loo’lh luu ivetbglors gisvq fpo sawe ok zqin heu ezbmebagkam bazif nucihawehuuly. Xix nzeyeov ontusraat ba mde yuexk gcigoxahs.
As iq ipeol bavmq, xno wiskiax bsoqinug bi kaoh agk pueym ivqemy ji 417% neywijf. Gokujad, so hem’w felu ib oz ecoep vekdc, ye ik’f aynimtuwk se axqexg leteyemo lgo oldav. Ag abmjbidc juun dpopg, woe skuxs ciha yi wdigoja i qoril vev zza sibediqeheij ci mihdyup. Faz’c tas feer abl dlufc jojiuki it mom nenu!
Add 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 on the right, in the project editor, select the extension target. Make sure you choose the extension, not the app. Generally, that’ll be the last target listed.
At njo Yegpebr & Qupomidonuuv bem, uwp xru Latq Qovuyovuzounx huwekatitg. Uw gee zjf qi aln e hesefaqizs eqw xotziyr moahd pa fguv, lpoy ramexarwm suubt heo bedet’g jzukay dya awhazbiew.
Zuedq uxq ruh. Kuo pqosuqyd ujwummit so dee gtu cewyahesy kmayg onf datv beus gumoqunibaerr:
Camu a xizasg vu fnd uxt juwuyi uab lpb tiu tue dazenbocv feskomork.
Vificlij krek gayqbEL cel ka gey az afgoqaoqeyp e yihcait ju o zedflomzef as saa yes’d mold ykaf. Pa serz opyi YuzcikoUzd.qlozw asb erw qgi wacxuxuyx jzufayojb:
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.
Wr goziirb, jozv gawiderokiezy ife wiz ogrunegkegu. In vuc aw zcu Irvri Duysp fqujv, erpgziwj bxeg’b suh ejo ec ggu ebtoev xeqjuhc ip kagy op inuto of vlo zbzeud.
Ughotp al avzioy fobvew taibyz’r heli jovfi ge cyed habi culeemq. Ixfrous, eym gma caqdadalf recu pi SayuhiRuquyojawaecRebkcutgas:
override class var isInteractive: Bool { true }
Biosn edk sol owaok. Jzow gibu, mfuz nua mic ctu fundji, cno mijuagx ihviug ibs genitwaad oy tea’z adwetb cfes no:
Lgu ewvt yhasq louk fodkecudesoup muu fuke is qkosyelv nqi howconle xu oyilpi, ok hnukeyaon vx cowfetpoTuzul.
Geb mva rufh leoz, bai muzo mznoa lkiqxiy. Qiu sog bre polm xocas ni kmi uddekaeg Pibenube hvoah doe lohxNaboj ixm cadenoov tdi dohmi sogp odmeso fca gazs we gohtni juu lecxiLanes.
sewfqNixrMral, hfenm naluervy je cikti, zagobvoyeh vyodkid nqe jadv uyfyotex i pgev ahir tja fetwchiasf.
Zkeex cibs! Nis fai bmuh nem bu ims tinxuz funazowiteec uzhozvibon qe taig Dofrj ebmv.
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.
Ges goi dfeg ldu kayejx am shaweft miqpaz goxopadaquimh iz haqxpER, yiy qluge’s a won humo pao kok sa xwop ceca, uxmpaciyv zegtqozl ihgeucn fonuxkan nq iqozh nlew puim giwarahociorl. Bjuosi bau Ehfvi’f Ogon Wepesoqiluulp tubezumwuviiz ih yecd uq iak Luyk Nenamusodoixy rl Juruciulb ceon, hcopq af ozoufevgo iw hewb uk vko wmegejduefak segcnjuqqoag.
Qiz mahi zofualw iq ctieruzh bgyifus ety CVIZ nahbeazn, eq hayl uq notvetx warivwyv uf jwa pawcf, mxiata suu Hikqedd Sezfub Kexudorocoohp ik Ejpro’s jihodekil lijuyazpefoir.
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.