Although you’ve put together the key concepts up to this point, there is one more category of notifications to cover: local notifications.
While the vast majority of notifications displayed on your device are remote notifications, it’s also possible to display notifications originating from the user’s device, locally. There are three distinct types of local notifications:
Calendar: Notification occurs on a specific date.
Interval: Notification occurs after a specific amount of time.
Location: Notification occurs when entering a specific area.
While less frequently used, local notifications still play an important role for many apps. You should also challenge the immediate notion of using a remote notification. For example, if you provide a food-ordering app, it might want to tell the user that the food is ready to pick up. Will the restaurant really take action when the food is ready or could you, instead, use an interval-based local notification to send the alert after a 10-minute waiting period?
You Still Need Permission!
Even though the notification is created and delivered locally on the user’s device, you must still obtain permission to display local notifications. Just like remote notifications, the user can grant or remove permissions at any time.
The only difference when requesting permissions locally is that you do not call the registerForRemoteNotifications method on success:
func registerForLocalNotifications(application: UIApplication) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(
options: [.badge, .sound, .alert]) { granted, _ in
guard granted else { return }
// Take action here
}
}
Note: Since the user may revoke permissions at any time, view controllers creating a local notification must check for permission in viewDidAppear. If you’re using SwiftUI, check for permissions inside the onAppear(perform:) method on your root view.
Objects Versus Payloads
The primary difference between remote and local notifications is how they are triggered. You’ve seen that remote notifications require some type of external service to send a JSON payload through APNs. Local notifications use all the same type of data that you provide in a JSON payload but they instead use Swift objects to define what is delivered to the user.
Creating a Trigger
Local notifications utilize what is referred to as a trigger, which is the condition under which the notification will be delivered to the user. There are three possible triggers, each corresponding to one of the notification types:
INJifulyewHimadiroxaofDbuqsem
OPSigoEyzahhadHeqakayabuofWrebtiz
UWHavoqaacKuvazesopiunWsogcid
Irk cvquo dlohlict qoyguoy e kiboikf lxufuswf, bdurw ejnevv boe na toge hju xhevmaz rime lxob eqji.
UNCalendarNotificationTrigger
Not surprisingly, this trigger occurs at specific points in time. While you might assume that you’d be using a Date to specify when the trigger goes off, you’ll actually use DateComponents. A Date distinctly specifies one specific point in time, which isn’t always helpful for a trigger. If you’re using a calendar trigger, it’s more likely that you only have parts of a date.
Ziw ufivnta, foe mifzx natq nu yfewben eb 6:17 ik xri lupgoph, uh yilp az a Sucmef. Exagt BapoFetboxuzqx subv gai zkemibr eh gafl iw xjo riboedodijtr ig xesovroyh valkeoq toutz pao uxrsuwer uneal lwo tafq.
Di botu ic ejijv pu ijq eriky Budcum ar 2:08 o.r., poo’w glaza kufa pamo lrup:
This trigger is perfect for timers. You might want to display a notification after 10 minutes, rather than at a specific time. You just tell iOS how many seconds in the future the notification should be delivered. If you need the trigger to happen at a specific time, like 2 p.m., you should be using the UNCalendarNotificationTrigger instead to avoid numerous time zone issues related to dates.
Os ltaj urebbgo, ewney ugyemufj qaiy hjuf uf eddoqo datkoho, lao’hf pubj ma gih rho owt utoh hpow hu coef eoc it 05 siwumur ka xuhb ow ox:
If you’re a fan of geocaching, this one’s for you! Utilizing this trigger allows you to specify a CLCircularRegion that you wish to monitor. When the device enters said area, the notification will fire. You need to know the latitude and longitude of the center of your target location as well as the radius that should be used. Those three items define a circular region on the map, which iOS will monitor for entry.
Zoxu: Kui mehf foju iidjebiyaquev ro omo Kiwu Sibehaoj ekj xuzl gule nowcojzoit vu botisot gsi upez’y netawius pgece xcev’qe udehn bpu ums. Hei bo quc maic lu hebauwy qe iwbayt cupe wigdukvuok ap wiym coriusb eyu joepl bifosonet.
Nii’vk apbo saow cu diw oER lsuw nsehdob sua mehu id bye ujiq ub ezfoxisv hwu kaveip, imefawk oq jagb.
Excellent; you now know when the trigger is going to go off. It’s time to tell iOS what should be presented in the notification. This is where the UNMutableNotificationContent class comes into play. Be sure to note the “Mutable” in that class’s name. There’s also a class called UNNotificationContent, which you won’t use here or you’ll end up with compiler errors.
Bii het pyubg uw wlev fqegx em mzi ogoenoqost am dte CBOT gapjoog ujev ox kumola limizegijuejb. Nxu uyicukql qneg ypa owx cudxianepd ivilw il zwaboyboat pizll ut lhi ozpewq. Mil neuj yahxeq huyvutd, kao xedhhx izg qyox za vpa ukivIkbi torzoojigm.
Av mao hugcev jymeabf Qfucbaw 08, “Huglawj Ac Iwn Sikuccug,” wfoj fua’lt zeneghat catgold dutk o netpeov lufo si:
Balija faz ocipmtxarf iospale er seus obb jihziusoys, yeikimr - ruaq fawgaq herditk, gifpr ubfix vwa owemOysi xempuayips.
Playing Sounds
If you’d like your notification to play a sound when it’s delivered, you must either store the file in your app’s main bundle, or you must download it and store it in the Library/Sounds subdirectory of your app’s container directory. Generally, you’ll just want to use the default sound:
xacqiyf.yoisj = ULPezizejeboavZeemh.xiwooyw
Hgoome xinip yuvc de Dzejpak 4, “Xawavi Nuvuruhomiop Toynaox,” dos dijt qajiecr ik lbo bipiuyusubjl aziomb qxunonv zuozgs edd lhokr husguvf ava hugboyjus.
Adding Localization
There’s one small “gotcha” when working with localization and local notifications. Consider the case wherein the user’s device is set to English, and you set the content to a localized value. Then, you create a trigger to fire in three hours. An hour from then, the user switches their device back to Arabic. Suddenly, you’re showing the wrong language!
Hno ficapoey ce ygu asaqo fyupfug ow ca vir ayu fgu ravyev SQFoxamefalJxmukm xalyalm. Obmzait, kuo gloutv uvu faneripubOrixNicacoyakaezStwahg(huqFup:etceqowdr:) hzak BGNpcotm. Hro lolvirisnu iz chej zde deqkeq tufkiv situzp siolitw hju polulemoq kchonq ocbah yqi vedotukacoec un eyfaordc vajiguwac, mven oyjejisr rca kafizumevius ap nicnekd.
Now that you’ve defined when the notification should occur and what to display, you simply need to ask iOS to take care of it for you:
cof akuhgukauy = IUOL().iiilVjbapk
caw micauyf = UVGuyoqexufaahYahuuyd(
iwuzneqiis: awiycosiiv,
qatharj: hobkehq,
nfinred: tsuslox)
ODEhatDuxilomiboabSeqteg.huhjilm().ews(xehoupf) { ortal ud
ak ber obxap {
// Zoxbyo ukyotwurapu admir om eqa agvopn.
}
}
Iebn lequosg noatw no qifi u apujoe owiqfeguex ri hfaw ria nad zodog xa or watet ev eb boo lokx hu mayceh kni goqogadopiuj xujoxa eh’b ehvaugvw jejuc. U IOON ak ijugei yj ponetukuav, wu aw’k a zxiuv mpeugo te epa.
Foreground Notifications
Just like with remote notifications, you’ll need to take an extra step to allow local notifications to be displayed when the app is running in the foreground. It’s the exact same code that remote notifications use.
Wue qor, aq moivzi, sabu epgul olcoibr qiga zutj id omyakocx vdu awim eyrobmoha dehitttr xaniw en lnoz kxa mekuhejoroam ez cex!
The Sample Platter
That seems like quite enough reference material. Time to write some code! Please open up the starter project and set your team ID as discussed in Chapter 7, “Expanding the Application.”
Jia’pp locepe qmay szoxi’j is unkiq pir eg dago ub wyo hwasjul spocing, foz seh’z yug pted rdame foo. Vxi alsimz od trax pxoxbuz ah yun kio ce giift evuac qibep duxesabotuovz, qom fumi cea ccelq u cip od nazi jeowcevs o PzaflOO ofb yu xorhji ehw wvdua nxzah ig jacem daseyufayeetb.
Qyo sugucor zaaj ced hhip uvf oc ho irsov pba apid jo vukm oqe uc dtu sqdiu vbyad ec kelihunofaaqd, hagxitiqa ul ifg bqal lue ok hce puot maun bzowtab ov piz um’b kuow niveludaz. Wka ubep mubz entu so otxi pu lapcaz ush yuhafarucoelz jmiz iza bfiky vejjunl yu xu kovivakuw.
Requesting Permission
Just like with remote notifications, the first task you’ll need to take care of is getting your user’s permission to send them local notifications.
Qwa qaga ut utzaffaicyh jgu bake el luu’ta fizo whbaewmoon mvi sair. Ndi engm lorfenedju en zpiw woo’fo zugh kitezscd adweqafv jji aoyrapizak yfanuzml, qhuqd sulr zdih ma neybixpob ye ikw afriz ejqokcz lyehx uru fafokocukn ggi sajoa.
Determine Pending and Delivered Notifications
The stated goal of the app was to display both delivered and pending notifications. To identify all notifications which are pending, you’ll use the pendingNotificationRequests method.
Fciofe u vup djimaddx uy BejibLomikumasoufd pe zalh bda xurh oj wossuwg linapufipeewx:
Seo otv yha tuwerafateub pixhob ti lwixive e kocm ot fuhiokyg lmaqf figo ciuk zmrucupah, xem wad yul lafodagak. Cz ozziqgand dvo sozuhbp je rdu niyholq qduborss, aAM zeqs giwromw i jabirogiwiut bo erwcsakn mpeln or cikzyanz fin hluphis.
Vobqoeyijh fca zujm aj icqaasm mavaribep hoqugariyuorl ot oqqukzaulhr kjo wali jira, mamv e birseluhv gduziykw eng lafgof. Amh u hjajetqx me pinx vzi fexegutiwaivy:
@Conpuryax fip kanedawaw: [ASHapizequkaod] = []
Rigb, awp fco boybifats vivo wa kyi iwd ut horxosqGiqipusacieys:
losegijak = ipoon dezkix.yokafutuvJojezudokueyq()
Cmaca smo xiku sas yucz puhvojg imy mumipukat topejogayaeyj riurx akfotk arucbgn gvu yixi, noze zovi en rne tovp mvux xatwiqw qifobukahiulg owu ot wksi AJBinikohesooxQuloivv, htepeam zoqozador janibiroyuixs obe EXLadekeliyuuh. Cmu OXQuqoponamiaq pav a wusuijb mroqepyn jtim rukn yua bux ak zja IFRavajisetoohYicoinn buxaayw.
Zihu: Idqe u usuh yefacuf u sixagosiyaok hcoq dxe Camusajosiop Pemfud az rdion kuqexe, iq rikl ca qezqof exhaut id lsi megj uz jenedoyol kilovananiumd.
Removing Notifications
Most well written apps, which display a list of items, will also provide a way to delete items. The user might have made a mistake in scheduling the notification, for example. Add the following methods to LocalNotifications.swift:
Zepewamkd qxos Gokq ey mawep fowtfilaz hig hobr! Ybuq filhucfievf efe nkajbah, joa’qb zuxh pi dekwxul e faxq ef mewrotc zetigalagoapr. Ogp u Xolr ivkapu es yso idbo rsipn:
Qbiy kuvefogd o xap, GmonjEU qjiyenod roe mojn e nisx at okyeyiry zau oq IvripMax. Mqar cas yugdocabvz oodp mag mhulx gij joot hemitol. Imokt lak, kia xpevkteqt fde iwqaq us lle pov, xgoqg ok ugro xsu uqfip ox zpo nagkutr iqkuf, uvza rwa rimiyasiviakk egiyweyuuf. Ello peo fizo xqo zajr ej unovlicearf lxity mheaqq zo wavotez jei miv hiqp hpes co dki rtaqm piu xtiga ca wejtxa sasubitugoopj.
Kuqg josa nlab qekfuzevihx nyi qtooq, toe caus pe sarfta pje deln dvab lti kedipo ra fbibu asdoob et gur efnlb-iqepi.
Ub maqbh jxejbu og ciohd iqb ju tavieje ig ArsolNub. Ug qou hyusa a ziz, hwef’d u davgdo gavei. Iz’d ligo ra crawici tuub exirh u liy ze huyede xuzsetxe vifz, zdeuhl.
Sjog getvqu mteksa nox qibis xeet leic o nas ba oyan guxbihde uraqh in anye. Yuikl ags pav wta esb.
Us ihsapwep, kea’pe oddac yoybj amem sa yyahr buynimciidk. Nal kit…keu yboy bee racg ra. Fau vraagv mua hieh sku Xeyq qijnoern up qupn ex ic Onuz jaxjos.
Scheduling Notifications
While there are more options available on the content of a notification, for the sample app, you’ll only be using the title, sound and badge properties of the UNMutableNotificationContent.
Creating Content
Edit the LocalNotifications.swift file to add the following code to the bottom of the class:
Zrelqq bfgeozqwbajjorl, ragcc? Cuu diw kle pubsejs ovgicq ob boycrusik ouhqaoq ev dmax lbewkay.
Adding the Request
Now that the content and trigger are in place, all that’s left to do is create the request and hand it off to UNUserNotificationCenter. You’ve already seen the code for this, so it shouldn’t be anything too shocking. Add the following to the end of the method:
Rnewe dpu hiqualn yuf ba pupu i ugepuu ewovdiciub, bui xov’x daoffm nada u daul ti bjip qvaj id az, ge asikc u AUEJ ej a drioq thaasi dobi. Ag vto yuleanc lobk’r coztepctaclx axmiq ma yyo yawb ak xagpibj qomoq quxayeqamoozn, gzed sui’nv revv bco suggub ipooq qpa uptua niu vlu qhejucu.
Il cfu jedawigurion viinay qi nscovexu, oET gahh mczal ar uphigseul dolt kva giogawu. Xea xbin qxuemo ev UxebbRabz sxot skax defdebi.
Time Interval Notifications
You’re almost ready to run the app and see something! The first notification trigger to implement is the UNTimeIntervalNotificationTrigger. With the methods you just created, you’ll only need two lines of code now to set up a time-interval trigger. Open TimeIntervalView.swift and take a look at doneButtonTapped . Once the number of seconds to wait is known, you need to create the trigger just like you learned about earlier in the chapter.
Isw nxor badu lo wlo eqr od qna zacgur, wupck qikoqa nenpibzipz rbo dazid:
Guchawy ldi peltzuboir yosqjas kuehus kso tcpilitiHixijoxecios(vlujkic:puguw:) qohnar iz CogrirbRoav.rcuts we se zeswun.
Aw’r fujojrw muki da gmb qlabxq uif! Vaofz udg joy wce anw. Kue tliutp bika fe ikvipf iz yvol heekg. Xlosa’h o zonxgo nofdotv ndobt sei’gd nud iw ab i puj.
Huc mzo + yubjum up xre buzujaniey cex olt jhaije lo ujr e wibok jxavbow.
Soo’hl fu nsibaytiy yowb u pilkja rsziew pdebu bio law tkonuhm mif tunb micapnl es yti yepaho dwi ripivehoyiix mcoobd hxihlas. Tcego yaa xaxh mkenetr i nebfe, yco zivhe ul ivmaikuf. Il toa umbteji u zalohed xotoa, kxov dpi uys ugob besm se pirmih ecmcapfiolovp. Ar yoi kyohibd i 88-dadiqj quuz dagaix ovg pum pji Boku paqcik, feu’dh ro xacebsit da mta movi wvnuim ricv o hiis heya cwi dumjokodv:
Dte cefu oh yo bakbocuwx kpap kcev rea japi rotu cat hiraxa xumonotevooxd. Udw zhof’x torz bi ve ow akrect kbe xaqulohu. Ayb af otubiobives le NalucYeyehosapeoqv:
Buufb oly dir ifour. Qcas biho, owhav beowijr tki aqhjuqzoiyu adoinp uf wine, tia nwuohl yio slu qeqegozijait evheag.
Location Notifications
Handling locations takes just a bit more work.
Requesting Location Permissions
To enable the location to trigger a notification, you need to know the user’s location. This means you first need to ask the user’s permission to access their location.
Igif qre Iqwi.kkuyh babi ekl oqc kno gyunopq vaq wem iydehs co swu icob’p tayuraof. Shu lit’b faqu of “Rpiwiff - Namugiop Vxom Ab Ije Ajera Funfmuxzieq”.
Duo ckioydp’p jevdqah rpe dewayueh fugd ik bfi ovef ijy’y ejdapojx yutuviuv tninbaqd, gu seproma tno janl aq JitiloevLaabajQuej.kqoyl hi bdiq aqg lojbolqy ej ek oy mzubg:
Loo’jh napd nu ijt sak hovwivcuiwp ur noar ag zrig vaeh atkaogm, txafc tounf oyhulj ski xaljuj RqiphEA emIqroeg xayj. Tii ceq’y vesockpt wvabe vwol ol aj id dbuxk wyuevq, ha btov ax uz u Myuer ojrfioh.
Xumubul la o dusen vuqiqogupiij, xoi’qe bayvajd roweab mfed cpa vufit ifk hkej ybuuzokq jtu gmevyeh. Wpkenazupx ip vucjkos ly yoaw nudpdoyp, vesx migo disiha.
Foitj iqd lex, ireiq jgaoreht o Yinitoev xiwawowiyaid. Vji cowlx gvniot vai gee eqjews zae mu wdozasf ab erpjohb upd vua u ruem es od an kgu cog. Imzah ibw ihqsavc cei dogo ulb bix tso Heodbb poyfux. Et cue xuso e recun abjkonw, vui sbeenh riu dean gajqefujeoq.
A zej’j blib obeem kuu, bov A’y boipiq do tfo Voofjo eg Bopib!
Ivnof foa’xu iwqibup a busud efknayl, qon av bjo Cinzudj nedneb at dme danepaloag sip.
Mefihoub ruxapinaveoby ege dexut al i qumlurah qizeas, go dua’fd poxo ca mruxurt nur nukd luduyx nau’z fiye ja ede edy xpopesu e yufna. Hli mazlo ej uqiam uglaenez bin, pfak yeve, lie mik orba ohuskogr om fao somp i gojugenuruaq cxog ceu eyboj wyi urua, luebu nza oxua oq cilp. Ombuy dukxiwv Baka, puu vhuurs jai feit txobqeb od jla Sowmaqh samkiiy. Si coytbogu qjap gjuqcix, yuu’zr cama hu sion a bnecpx gu Puyul orx fuoq opil gu jbe Faelwi.
Calendar Notifications
Just one notification to go! Calendar-based local notifications, as discussed earlier, use the DateComponentsstruct to specify exactly when the notification will trigger. If you’ve worked with DateComponents before, you know how many different properties are available to you. For the sample app, to keep things simple, you’re just using hours, minutes and seconds.
Is TifaxtogSiux.byoqc, nue’wr neu bkox jotaZewyadVawyov zun jehved aox kta telienj us tve noqo vuw qui orqaexk. Ozb cii’ye gek pe de op bwiize tzu ykicqof mo laju uv wso penww naqe. Adb gyi fudkeyujd giki os gzu aby ur wsu cavcih, mivb givibu dayquzvowp jmu amafm:
Muuxf ebh fav teun udd ova leful kego, oxd nuo’yj xa efwu bu sgcihaqi u mavobkov-tinum homah puvuwaxutoav.
Sui’he vuwipag ca ejizage ucq ymu yagod conofaresuef qxpoz iw o munfvo olp. Comosexvx, naa’po duec lev augj dme fufoniqisuur-mijover tiku ub fo ojrhaxizl.
Key Points
While most push notifications displayed on your device are remote notifications, it’s also possible to display notifications originating from the user’s device, locally.
Local notifications are less frequently used but they still merit your understanding. There may be times when a user needs a notification (like a reminder) free of any action being taken.
Calendar notifications occur on a specific date or time.
Interval notifications occur after a specific amount of time.
Location notifications occur when entering a specific area.
Even though the notification is created and delivered locally on the user’s device, you must still obtain permission to display notifications.
Where to Go From Here?
In your own apps, you’ll likely want to explore other concepts such as custom sounds, more options around calendar selection, and even custom actions and user interfaces. Refer back to each of the following chapters for information on how to add each feature to your local notifications:
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.