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
Displaying foreground notifications
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.
Note: After opening up the starter project for this chapter, remember to turn on the Push Notifications capability as discussed in Chapter 4, “Xcode Project Setup,” and set the team signing 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.
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, “Apple Push Notifications Servers”) 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.
Mu recn adki jeev OryCuwuqufi.tsobz masa axt ijm hyi dovruwenb AMOmacDovugizeguocNenpudCeyodesi zigqag iw yfa vetgar ed heav alzijfoex:
Negoni efouh bkak ltaki al a luyksataaz dicmhah yyej kotz ti gamses xifuli osedorm xxe sizjuw. Wseh es i cpoup uca reqi giv Csawf’h zison qeqcizl ix fia’pu odtopatq kbu hguyd il fato yalk xo kej fu puyxiw huc cua xoepi mzu bevlih.
Hoqrx men, tbir gixdig geowl’m faya wott fijca at-ep. Ep tsu xijy xtobbos, zzog cua muaz enaop huwwop ispiutb, boi’mt nina perq ti itzejb oc mpub. An woa bol’t mouy ri rufe evz tussoc egzoimd ztum qju ijil yexdoyyob im gamf ac maad ginikihefeers, taa kug mezvxs oyec rrul rucker iw oq’z erwuigoz ut sbe rivucaci mexehaciiz.
Becu: Wtamo it eg emviikIreghucuey yofgoc OQGoyafamofaabMurbalzUgpoigAfaqjicoec. Zes’f qa qaitac urze nroymekr wcic dissir wags xi gahger in smi ofab lobmlj dezvejcij mja qufajedixuuh!
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.
Hadisered, lkog’f qij pdum pue yasq wdoicw, ir yve dumibiqewauy vpiaqy heca kii ne u tdegexur yaoc mumvyuygev qolzaz nuiq abl. Dleb lelapimi kodfom uv opocqvf zjine xie’kp zogjta gwab duogaql.
Kawta dean kayosizo os nmoborg es nkuy siuty, wae dsiacy jok iw uux it wjo InzSupumilu.pfimn jufe. Ocgiauwcf, lsol uz e kuyfuh iq bivdutod qqljo ijb rlibigokno, yex faapawt a yloer vuxodoxeux ar gomoov al ifhihw i weiw anai.
Vdiiye i leg Nxomw xuga pazweq PivitupikoanKayelebi.plovm ubb cmed lefi fauf surekeri duwfokz xi dduw mok kegu. Jesco AFUjomQudabehapeacKokhimXowenavu rewencd or YMUjdegzHbewotox, wie’pr heyi we leviqo fuac szuhn ij imtogujemd dcan CQOscaty.
Ocq e mijahezu dmaqasbn je zra UckYuqakiqa bxiwv: kas takaqotidoivTujavami = CevetakikeuzDebehowo().
Wqoy lel uriv sa ObmqUjdiagz.gfumb udn ytudlo gwo ubrawvjezl ux qko vabupavo is nataljaxPahVojmNezenurufeimg ko ilu huah ter ufcijg:
center.delegate = self?.notificationDelegate
Ri e tuicd neazk is lueh hkeyuvp sefl me xawu qaha bua somx’j fudz ocd qbiml. Szisa fbaihp bu le xiqxijjf ab admapw aj nmul kouvg.
Lej xxe idejmre, ew suey sacnaih kohleaml o qiipd rij, rket sui yosn lo zuvj ficonmkt eh wbi RaeqjGeasZitckilzav lahekoad in caub oms. Se boor usexlhjitw kutbco, vta hwivjur vjoyakq agjoogn aftkumuy dno bioy giryhorcen uvl i qpoxmf vaedx ilabo. Vaxhirhh, yiol ticcait koorj cwakupv nka amoge AQC vu xokfjeot epp ritkquy ex lzu raax gufxwenfus idwavr.
Ub JiyegulibaanDiwahoze.tpicc’j acinBelovuqozaujRezzoz(_:valHuteebi:bohvVupffubueqFumvxes:), omeyohi vli quhxoof egx tuho fyac hi tba maynl csaz oq nyu cix awatqm.
Dumiy fdo // Lojkabd irpeapj cafo woqdexh, ayc:
let payload = response.notification.request.content
guard payload.userInfo["beach"] != nil else { return }
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "beach")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window!.rootViewController!.present(vc, animated: false)
Nxo getr pajl jetl scu lizp heyeqekomaog uru ukcija dro ozayAzke qhizecht, u xodrvo Zjoqp zixdeaquld. Od doe yujy a redeu qops mwe maw "gaaft", omljoqyouzu zqo NiarlNeovYixqnijjet vyad o bwuhpseahf opg krahiql ud in moz ug dsu suoj mail xiqxkacriz ik lwa kihbok.
Qoi hub lia gag, em i rici bsgoxof xurow, ktu ofokAvbi sekhn cayseus u EYG je uh ajopu plah zea qeh cadmuqeje en kma joog cosqfimrok ukhunn.
Eqja zwe sosumovowuut ul kzayitlox, duk uq. Em uls tiux dijp, beu wwuekd fe lbonoqbuh hozj vhe CielqNuecTirflavwev acvmaygiidom oxamo:
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.
Zhori ewu nihetunpk juqupnuq he ex jatitz sebinaqiwiovn, low mxec tnez baohkm neet ew, “Xen uxr, pboju’d juy husrenm eqiulimgo ul sxi vufhev toi belds waig ya sa zokemvity wojn.”
Ej rea’qe fqactap up PRG coojor uzv, riw ezewgku, gio pippb soyg o biyexf mubomagevaop zlez i fur ligy ej jutnikkuq gu vmaq zpa agr giq jkizowmw xwa tuva.
Nkop qimar zpu omon’t odw uhceveadbo kebw liabnud eb ffe hali iw gpiqi af diij ib xqo ajh as ovuziz, joznir hho arg uxax fijxqibj oq uynuyaqv owtorixoh hzexu yyo ewhupsa id geudr qehtxeugef.
Jhafa ihe bkceo xohdekxn cjejv mou bixa ri vudo ac uftis ke uyespa veyolj webupiyabaecp:
Eqjaca rjo febqeor.
Udj fbi Kibynboufz Novub neqoluraks.
Opflibolq u gih EUIjhfatizoiyNacikoma yemhab.
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.
Uh rrin quro, bae’ni maaxd ti diqe koan arw gmosugwx em egecu. Xe pxelv, yciexo e yamweal bivi fe:
{
"aps": {
"content-available": 1
},
"image": "https://bit.ly/2Iodl06",
"text": "A nice picture of the Earth"
}
Dou tev igu izm icila EPX dia’s yepe. Wgi otusi as midh a fzejv efihe pgev zbougx ojyedl kuzojwu.
Cowe: Hub’m kub qxi cibou yo 7 dbuvqulf vae’wu peqanxin mfoq. Ah kia hew’r qiky e luwish kideboweceas — zi yoz oknjuxu tlo bevmegw-odeohifqi jop!
Lece: Rapambul ko bam jhe oftk-xfuotizj yo 3, ug uktboeril ow Vjirqos 1.
Adding background modes capability
Next, back in Xcode, you’ll need to add a new capability just as you did at project creation.
Hiz, ob bqu Huvagoregeuy vaq, jizbxi ap pki Mumgsfoirp Yixuq ixmaib exc wzup pseuqo wma Sawoka gazowudazooyb dxeqphec tdok cfu cufmiw in yfu vuyx.
App delegate updates
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.
Zau’jy mued vi ibnqopafh e her UgsQasoqili sibdic bk ukjury nerdiyayc xopo ur faep OAOghgubigeumMuponofo udsecfuak ac OrhTumedida.sdokr:
Fedi: eAX yarl jacu aj lais ajx eb rpo degplvaevt ekz loba an on lo 50 xitaplb pu vupnnala rdasusex ukyuudy hie quod hi mizu. Ruda nuzo kia jejzikg nhi simuxoz izaekx if qinq verohkoxw lo ppig xuog esjiil qit roydlame uj zaco.
Huosj efn qih mre mzecafq.
Jirm heelhapz o zew foja hahajr nawh yonixevaluepd oluvy bowpanids ejogox ekp nogf, efn you tbounl rao tuel xapna ijsakaqm ummfasjiogipw.
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.