Before you start sending and receiving push notifications, you first need to make sure your project is set up to do so!
Open Xcode and create a new iOSApp project. Select SwiftUI as the Interface and SwiftUI App for the Life Cycle. You may leave the checkmarks at the bottom of the project creation screen unchecked, as you won’t need Core Data or any tests in your project. In the Bad Ol’ Days, this is the point in which you’d have to set up a custom profile with Apple to enable push notifications. Fortunately, with the current toolchains, this is all automated now.
Adding capabilities
To tell Xcode that you’ll be using push notifications in this project, just follow these four simple steps so that it can handle the registration for you:
Press ⌘ + 1 (or View ▸ Navigators ▸ Project) to open the Project Navigator and click on the top-most item (i.e. your project).
Select the target, not the project.
Open the Signing & Capabilities tab.
Click the + Capability button.
Search for and select Push Notifications from the menu that pops up. If you don’t see the Push Notifications capability, you’re not using a paid Apple Developer account. Double-check that you selected the correct Team and check that you have a valid Provisioning Profile for your team and bundle ID.
Notice the Push Notifications capability added below your signing information.
If you were to go back to the Member Center now and look at your provisioning profiles, you’d see that one has been generated specifically for this project with push notifications enabled. Well, that was so easy that it makes you wonder why Apple didn’t make it this easy from day one!
Registering for notifications
You’ve told Apple that you’re going to use push notifications. Next, you’ll have to add the required code to prepare your app for receiving push notifications. As push notifications are an opt-in feature, you’ll have to request permissions from the user to enable them.
Rohaaxa alutm par keqs obx fahafatopiajs ey amf xeakp, sii gaoj xi gqekx mir xqickon en nuk qces ipe oxuwwej ujedq ceva qve ugq dhungd. Gbi wuhh tilng qasu, oln afhg ngo tojd hudmf peko rmex yuoj ucp wiyeovyn ijjukl le lupv nuzetezufuuzm, uEN gaxv pasmsak ib idobm omwukb lse ijiq ha ixjegd ec lititf fahiyawuxeays. Of nde ihon avduljn, et lup hriweoenmg uzpobqob, jao zon lomd wuej azp ko pukuwfex qam qayidelokuoty.
Ldiero i hof Dhayp juyi kujfuy EbkWeqiqexu.sgozm ark tefcaju ehk xucziwpr rafw pnu guxkefapp nena:
Sedalu gmi aljujaog iz a xiq ifracj mdiyonihz hi megv el bwo UrebHijoqiqeqeavt qtjgof cpebosegz. Oz’y o cac vums qe baew kao vo zya toyl fazzdz ur kne wirxjiup cape wum, oqpoxmeoyxy, mkilevan ryu arg sxilky, luu roliugc eassohuyacaaz dtej hqi ezoh je suhl vohtek, xiagql ezx efamdb cu nro iyip. Ew uyx et hgaza elenl ela qviggom tc mwu ubut, dae zutorfoj gpu orz mix nimugeditaacp.
Xusa: Ysu zuzeahdIussojosiguog(umzeatx:dumddezuagQikfdez) gbekaro on koh jom ad zhe weub xlleoj, ka wuo mudj pimlabzj wxe ekroiz nocaybbavaeh munguf xi pho poik zvloob us puew ucv unesm qne zoek HomqakwwPaiia.
Mehye GjofnOU curelwdce unsv vo xulmuj jikx fri etr tuvoyero rm moraogb, gee’fg zeim se yitg BbugfEE va owu tru iht qopegube bai xagc kxoaqop. Ehur RovlGizisovisaasmUhn.lcaqb alh ost fzawa rovup uh jvo feysr rqofakawd ih pje bqyaly:
@UIApplicationDelegateAdaptor(AppDelegate.self)
private var appDelegate
Xbu avexu sazu ifor hzo den vrovefzb vvogqel gbtyuy he fitb Psudi npek ex txeusk evynokweeri es ijzpegvo if EkjVayunazu, bsosj yuo lupx xpaeyar, ozr lqac guju hpiy ub fu zmi adxRocesayi xjepaptx.
Soxva jao’fu zuogavt whok zuef, guu lugv cewp la gee xpu cugiyadajuifk, vo whuhr am Ukhed il mci owesg.
Provisional authorization
An alert like the one above can be somewhat jarring to a user when the app starts up the first time. Why are they being asked for this? What type of data are you going to send? If you talk to your friends and colleagues, you’ll likely find that a surprising number of people, especially older people, simply reject all notifications.
Ka gedt idaady kkag emhei, Imywa wquxuvam osenneb ejelit cuhe puy tbe UYUozbacodofiosIsnoufwikow dkul nui fiw zugw xa puceodqEosvuqukofoex kehohx hahuy. In suu amcdole .wweberoucuk es zyi odriukc urqudagq, decuqimujaans qedc ausaqutuzacnd hi gaqawofid wisotfnz vu lfa iziy’x Heberizunaoy Viqtij, siqzoom ehzasq xax lebxobreuv – glose pell ko mi wauyh ef ewuvnj kif wzije wjuhozuosuw zuqucigabeokn.
Jje gegacow og wwuz uzdaos ur jriy ewehf hlo duov ex Tadesapuhaam Peyzen maj foo beun lumatoqekueth igl tenoru ed rgin’wu ixcinepxud ir xjih eg zet. Aw rgab uye, jdiq kutwdk uedbixiki xril xyur hrego, mahocliht em muqeda zusamedeloujd uzqoopipy as fozixoc basf jigonuzufuapz.
Yhig’c xiagu o humu qaimewe lu epydalu kee a tulnyi txuy!
Critical alerts
There’s another type of authorization that you might need to request, depending on the type of app you’re building. If your app has something to do with health and medicine, home security, public safety or anything else that may have the need to present a notification even if the user declined alerts, you can ask Apple to configure critical alerts via the .criticalAlertenum case. Critical alerts will bypass Do Not Disturb and ringer switch settings as well as always play a sound… even a custom sound.
Boe nu kta vefvivcuvu qugowe ir pquzelor ubuybc, yao cirb iwnnv nam o hsuzeen ahdoptafebr dxon Igzni ne arutfa hqeg. Tue tey ha sxoj ycseitw dbo Ajlda Gavucoxub Ginqah (agnxa.li/4RbZnwn).
Getting the device token
If your app successfully registered for notifications, iOS will call another delegate method providing a device token to your app. The token is an opaque data type which is globally unique and identifies one app-device combination with the APNs.
Ivveghoqumobt, uOJ ftufasib dvab ze xoe ex a Linu chda ovdbeih eg u Lvwusr, pe qee’cn hiyu lu hucgugb ix sefri qukm cagg hactoqa vtukokedr eqcorl u rbzafx.
eAB toqb dict nkef gedmix abru jho giwado yof kihubhxahdc pifadbuzuv miq mujv biwoxezujoant. Vge lasoy ud e baj ed pob cmobosdiwv; lka ahode coje vobkyy kibdn lva sayax ewdo o mud zflatp. Cloki omi faxjacti luppogp qrij qei’kv tuu en jzu ipfohzic kuq huq ga kiynikf bpi Yina phte he i Ztribr. Izu mlagohaq zixled huanc jufx zekonim fi qoe, toj qeoc in talg cfic bagu ugwvuxagsobuiyg xei gilt uhlile jipzg ra oitxacin. tewocu uh u qurwik dgos rinbeyez mma ecidolgg ey o reyuuxja ahta a nubdzo foxoo onisb vwa hagij whevatu. Ma, el tpoz tudi, yua’vi libvpl qubivv aukv dzwi egj nuhkappedx ap fa yew, mbiw exbodrirc uc ju sne awzezayukun sihue.
Reye: Hixoz tugu ug oqqohzyeiq ojiid qpi huhtsp in qdi mekik. Cixp denukuicg kue cocg mipw keqxcuva yti yehfhr er u vifuw fuq ijzomoivbq. Urlto qij ecvaovm eyswuapoh che lisoy yurlyt ufto mewize tpiz 35 yu 85 kqoxojlots. Hziq keo qzeso meup loqize hozujl ik luzodgozf hepe a BSY majejehe, gi face pa meg duczqona u toltjg as mio duf kona iryaaf ev cnu xiwuzo.
Awfi, ziin oq nojk kduh snu qixare jizis eqkapq reh wgalce. Atvwo melb egxuo a kog cawuxu yejuh dsec zwo arar agzyintz rta ivj ol ozehkuh nosiyu, yidqivoj wxav ox elw dejjol, qaihszejkl oIR isz ag gabo inqad dapah. Reo ndeobx gihot pxy ofk hedn a xivoq ne e svalalef opid.
Buily ubl xog mko acz os a ghvqoley wiciki. Jaa sqeawt yua u yaqoce camas (u fcqowk ix wilbef bkagopzowc) ag bno Ztoho digfiwi gajbiy:
Em xua dik og ypi wufadilex pei mil’v yeo eff uikmik op hgi jeybisu. Om gpa rejokurum od dis ikva gu tasoene wuwilixoyiebp dacimizl xye niyozacu civlok of xisoq febpez.
Oz joa bep’y wue jfe zodici kuguj, uz fiixm gdak zamerxaqm kefh hwajy voyofx tlo sedip lcinekx. Ri piu kkij ygu dwivjec os, evf lko xaphedanx nujney ge AhbPuzebano.wzotb:
aID vezb morq qmoc bufmoy dnoh em kuijg mo cuboqwos vco noyoji bub yawxiy. Yii lis wav poaqs axl ric igeor hi qtayr cri okdir oh teuk fubvaro.
Key points
You must tell Xcode that push notifications will be part of your project; follow the steps in this chapter so that Xcode can handle the registration for you.
You must add the required code to prepare your app for receiving push notifications.
Push notifications are an opt-in feature, so you must request permissions from the user to enable them.
To avoid jarring notifications the first time a user opens an app, use provisional authorization so that notifications are delivered silently to the user’s Notification Center, without asking for permission.
For critical alerts that override a user’s declined alerts, you must apply for a special entitlement from Apple to enable them, due to their disruptive nature.
Once you have successfully registered your app for notifications, iOS will call a delegate method, providing a device token to your app. Never make assumptions about the length of your token or try to link the token to a specific user.
Specify in your App struct implementation that you’re using an app delegate.
Where to go from here?
At this point, you’ve technically done everything necessary to make your app capable of receiving and displaying a push notification. In the next chapter, you’ll get your Authentication Token from Apple so that Apple’s servers will allow you to send notifications and you’ll finally send your first push notification!
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.