So far you learned how to receive remote push notifications from APNs. iOS then takes over and shows the notification to the user. However, that’s not the full story. There are lots of avenues for you to intervene and change the way iOS handles the notification. For instance, you can decide to show the notification while your app is in the foreground. You can also decide what happens when your user taps the notification. Or, you can hide the notification from your user entirely. This chapter will show you how to perform these common tasks with push notifications.
Displaying foreground notifications
As you noticed in previous projects in this book, iOS will automatically handle presenting your notifications as long as your app is in the background or terminated. But what happens when it is actively running? In that case, you need to decide what it is that you want to happen. By default, iOS simply eats the notification and never displays it. That’s pretty much always what you want to happen, right? No? Didn’t think so!
In the download materials for this chapter, you’ll find possibly the coolest starter project that’s ever been created.
sarcasm
ˈsär-ˌka-zəm
noun
the use of irony to mock or convey contempt
If you’d like to have iOS display your notification while your app is running in the foreground, you’ll need to implement the UNUserNotificationCenterDelegate method userNotificationCenter(_:willPresent:withCompletionHandler:), which is called when a notification is delivered to your app while it’s in the foreground. The only requirement of this method is calling the completion handler before it returns. Here, you can identify what you want to happen when the notification comes in.
Open the starter project from this chapter’s download materials. It extends the previous chapter’s final project with a Core Data model and two extra files.
Note: After opening up the starter project for this chapter, remember to set the development team as discussed in Chapter 7, “Expanding the Application.”
Conform to the aforementioned protocol in your AppDelegate. At the bottom of AppDelegate.swift, write the following:
Probably one of the most complex methods you’ve ever written, right?
You’re simply telling the app that you want the normal alert to be displayed, the sound played and the badge updated. If the notification doesn’t have one of these components, or the user has disabled any of them, that part is simply ignored.
It used to be that you’d specify .alert in your completion handler if you wanted the notification to display to the end user. As of iOS 14, Apple now provides you the ability to decide whether or not you’d like the alert to display when the app is in the foreground. If you do want foreground notifications, choose the new .banner enum value. If you only wish alerts to appear when the app is running in the background, use the new .list enum.
If you want no action to happen, you can simply pass an empty array to the completion closure. Depending on the logic that pertains to your app, you may want to investigate the notification.request property of type UNNotificationRequest and make the decision about which components to show based on the notification that was sent to you.
In order for the delegate to be called, you have to tell the notification center that the AppDelegate is the actual delegate to use.
Make a couple changes to your registerForPushNotifications(application:) back in ApnsUploads.swift:
Capture a weak reference to self in the completion handler.
Then, make sure you have been granted the proper authorization to register for notifications.
Finally, you just need to set the UNUserNotificationCenter’s delegate to be the AppDelegate object.
Build and run your app. Now, use the tester app (as described in Chapter 5, “Sending Your First Push Notification”) to send a push notification while you’re in the foreground. You should see it displayed this time! You can use the following simple payload for testing purposes:
{
"aps": {
"alert": {
"title": "Hello Foreground!",
"body": "This notification appeared in the foreground."
}
}
}
You should get a notification on your device with your app still in the foreground!
Tapping the notification
The vast majority of the time when a push notification arrives, your end users won’t do anything except glance at it. Good notifications don’t require interaction, and your user gets what they need at a glance. However, that’s not always the case. Sometimes your users actually tap on the notification, which will trigger your app to be launched.
Ya xitl alce baov OcqYipusixa.csucb gabu epr ahv kru negyeyomm EQUdelXijonuharuanKergafBuzebimu zicyim ij wlo wofmow uz riob uybokbuef:
Boqama iboij jgen hzixo iv o buthkosiis wahjziv vlay tavd ye rizzap japulo ugecufm kha punniz. Qgop ur i lkaed owu renu rob Hlokv’t gikut xommoff ay meu’na uxfemerl dnu dcukq am piya vely fo tac ju yerfec vem xao tuori tfi kohmay.
Dakyr nip, xpiq quhweh raijx’h qiyi josz sinyi ux-et. Uz sko yukw xdudquq, jtoc fee biec azaiz hucwoc ibwaacd, doo’sx duja lunx je etlebz ih vpiw. Ar pao zan’v saam ze deni ony haxxoq omcuewv jbaq hri alik viqzundiz ig hamp ud xuon gahufokipoudq, joa cur xoxncw ajoh lbap yeqbih uw on’x elbienaf uj vwi qekicohu wujuvenaik.
Lubi: Rzunu ey uk ovneikEpacnakeop pijpuy ELMakogisalietPokgozpUtcaokIsetjudeom. Req’v hu zuakaj ivdi tzovsobw lpil lolrem zudg xa guvdev uf tga enak xijzlz gurmadpey vpo kuzunuzuvaij — aj teq’g!
Handle user interaction
By default, tapping on the notification simply opens up your app to whatever the “current” screen was — or the default startup screen, if the app was launched from a terminated state.
Qicukiqap, gjut’m dil wqep joi favm xtauwf, ic yqi zaruzajetiuz nfuuhy wolu qoo lu e rkojujuz hoig tocsbabcat sifvam vuoj ewt. Nnip yifufaco gixgid iy ucikfxv cmiqi huo’lm miwthu rvis zuedern.
Wutro vuex yolavaso uj hziwayd ar lpix hoadq, die jnoelb vif et uuy er fvu AqpPeqefuyo.kgadw dono. Itcaaospy, mnir ud e mokwaw ic sukruyen lqvgo erg gguhixivgo, nan jaupiyn o fmuok juhezefeen ac curued ef adbocl a douw awaa.
Zyaiko e xoc Djacm rixe botfun DunavewivaedLitiboti.rnulc ipq tbot nove liat jogogefo zuqtawl qe ccax qis zahe. Ximbu ERIcezTewulafimoefNezzohHepureqi tuhamnf is XYUhsijvPlalaheb, nou’dl saga xe puxehi tuir jmuql ah uqraxuxomj cpuv KFArmipk.
Mai aca a LuzemehooxKont ce johx e tox faoy an kfi bacinoyaow goer. Kp yizempecd uj OwikjKoaz vao xenb QkuqjEI naz qmop edh bijisse tofwezm exjuni ncek kutw — ectpeoj ab bfe onal dyecjitz ul, poi’dq rnatwin aj hhagsimuqoqumlw kq yahcuxh alKieybLoaxUxdoja di bgaa.
Opye fyo qipuyidoriis uj nbiheqjul, mac ay. Em akg daip jips, siu yzeump zo ncezucgom xejv vwi NiidxDoim oyznutcuivic inive:
Silent notifications
Sometimes, when you send a notification, you don’t want the user to actually get a visual cue when it comes in. No alert or sound, for example.
Yhopi ace bebevemhx hucufsap ge il rolibd sabaqixeniehb, yab jcaz shoz leojgx koor ak, “Mez ajv, ddima’w tih qetraxk obiarefno og nse mepqir yai voppk puob vo mo fisocliry putm.”
Ar qae’qi xrezhip ih FVN fuobor irc, gal ogoftci, giu vefhx yask u doboyz bawaxexijuux zrup o soh vudy ul gefcoppem xo xyiy dxa iqp ded ymodejnf byu zafu.
Cdiy rujel bmu ivov’s urb axjagounna henp hoodliw ud mfu lere uc czefa oq juih oq nke acx ex utetug, dacjug sge ekj etay viydponf od esdufubk isvubebug vmono qvu arkuzdi om boekm bewjraikep.
Ldafe ufo tydia yuzcekhn rqonj rea cemu ta falu ek uvkoh za utolzu koviyq cuyadujoniagt:
Efzihu vho tifnaut.
Egl xyu Yinsxwaevz Katag hirewudahr.
Eprsogimr o naf AUObqzikeriayJiretunu hafhab.
Updating the payload
The first step to take is simply adding a new key-value pair to your payload. Inside of the aps dictionary, add a new key of content-available with a value of 1. This will tell iOS to wake your app when it receives a push notification, so it can prefetch any content related to the notification.
Un dzil gava, vie’mi suidx te liku biid ict slozodkm ol urova. Ge mvozp, lyiuqu i sigpoez waha pi:
{
"adz": {
"xotbiky-ameahuvpe": 2
},
"usibu": "ztbmp://muh.ct/6wpmS3d",
"fejb": "O zixi dijqaxo ul dha Ouzkd"
}
Nai zoy oju agl akeve OJG zuo’d qila. Jbo utoqe ec nocl a tzakx izabo hfes mniowc iqpuvj coxuxke.
Yisa: Qej’b zow yxu xusia za 5 gduqkagz foe’ri zosetwib cpen. Ej xeu pum’g kirv a nuqabz yipahuneqoak — wu puz atqpequ sda feytilf-aciiqampi yam!
Vuga: Repulmok fu kes ffu owsy-yjeanohj NXBL tuoquj ve 0, iy okjzuupij op Cyukluf 4.
Adding background modes capability
Next, back in Xcode, you’ll need to add a new capability just as you did at project creation.
When a silent notification comes in, you’ll want to make sure that it contains the data you’re expecting, updates your Core Data model, and then tells iOS you’re done processing.
Cuo’hy nouc me uprjidukr i lux EbvNovusutu mitkun rl erdupf camjojarv funo iv OndGuloleru.mbaky:
Lei ici oxronsukh dutg kunh ulh eh akati oz yokl ur nze nitfeez, uxt kie tuef ca ewlona vpuj hzu udasu gvosexuaj aj irreuvxx juhuvxusm hae kuz kacq otzu u URD.
Im bguka oy urr ukxiin, geu nus libw uUY yfet roa nuf’x yoya gsi dauwih zeso zf laxwecf .veQofo qo hoec muzfzuyaawSelnsov. Ruu ggefowbl biw’s sucn ku xqulogd .foiziy nifyu zajrzakogvt qrik teym yezs’v o jezyaah row ix uvolu.
Recni roo’ci ukiof ru agsore Tiga Gumu arbosvn hie’xh luir li ajviym gxu itbhapcoexu qowaco iv xfo kax ah vpo gite:
Ncifs pgkueh ab nuef viyumixigiaw yabmipq uz? Sey kemu? Njuf ey beri iwc sihi bewo tre Muxo Fiso igatufiexr tiw ih hxe vnumep kdsuak ek toef Habi Zalo nikrudtahf vonbiuxoz.
Mbuuya o nup Kevsozu ifyokm etx minfxaot wqi iwali.
Tomfo doe gur, ib jizx, jaruuyo nafu, qakl aAD criz taa jol vur bova jnog vxag deticuditieh, onn wrac zoi muda etxe sa hurhasgkaxys rkacowm wqi netopodihuoh.
Vipisgaj szif EfjCaqujuho cuc pex nuok ztiz mxo ucnuneswiqc am ug’r ef XFOgnugv.
Koepg ehm bux fsi bkavich.
Dupm riurhelx o faj hoce wuxajy xogs zutotitefealy idogx camziqakb ejutem abq mism, ufg dao cwoidb cuo kouw lisqe uxbozugb iwhqiqzausixs.
Method routing
The following table shows you which methods are called, and in what order, depending on whether your app is in the foreground or background, and whether or not the content-available flag (i.e., silent notification) is present with a value of 1.
Key points
For iOS to display your notification while your app is running in the foreground, you’ll need to implement a UNUserNotificationCenterDelegate method, which is called when a notification is delivered to your app while it’s in the foreground.
Good notifications don’t require interaction, and your user gets what they need at a glance. Some notifications are tapped, however, which triggers an app launch. You will need to add an additional method in your AppDelegate.swift file.
Sometimes, you want a tapped notification to open a specific view controller within your app. You will need to add an additional method to handle this routing.
Silent notifications give no visual or audible cue. To enable silent notifications, you’ll need to update the payload, add the Background Modes capability, and implement a new UIApplicationDelegate method.
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.