At this point, you’ve implemented as much of push notifications as most app developers will ever want or need to do.
Don’t give up now! There are still some really amazing features you can add to your app to make it shine, should you so desire.
In the previous chapter, you built an app that triggers an action when the user taps on a received notification. Sometimes, a simple tap is not enough. Maybe your friend is asking you to grab coffee, and you want an easy way to accept the offer. Or maybe another friend posted a funny tweet and you want to favorite it right from the notification.
Thankfully, iOS gives you a way to attach buttons to a push notification so that the user can provide a meaningful response to the received notification without having to open your app! In this chapter, you’ll learn how to make your notifications actionable.
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.”
Categories
Notification categories allow you to specify up to four custom actions per category that will be displayed with your push notification. Keep in mind that the system will only display the first two actions if your notification appears in a banner, so you always want to configure the most relevant actions first.
To enable the user to decide what action to take, you’ll add Accept and Reject buttons to your push notifications.
You’ll first add an enum to the top of AppDelegate.swift, right below the import statements, to identify your buttons.
private let categoryIdentifier = "AcceptOrReject"
private enum ActionIdentifier: String {
case accept, reject
}
Use an enum to ensure you aren’t hardcoding strings for identifiers as you won’t ever display them to an end user.
Once that’s done, just add a method at the bottom of AppDelegate to perform the registration.
Here, you create a notification category with two buttons. When a push notification arrives with a category set to AcceptOrReject, your custom actions will be triggered, and iOS will include the two buttons at the bottom of your push notification.
While I’ve simply hardcoded the titles here for brevity, you should always use a localized string, via the NSLocalizedString method.
Note: Even if you don’t think you’re going to localize your app, it’s better to get in the habit now than have to go back and find every single user visible string later if plans change!
You only need to register your actions if you’re actually accepting push notifications, so add a call to registerCustomActions() once you’ve successfully registered for remote notifications.
Build and run your app. Now, go back into the push notification tester app (as described in Chapter 5, “Apple Push Notifications Servers”) and use the following payload:
The critical part of the payload is making sure the category value exactly matches what you specified during your registration with UNUserNotificationCenter. Send another push to yourself now.
See your action buttons? No? Don’t worry, you didn’t mess anything up!
The trick is you need to long press the notification to reveal the buttons.
Once you do that, the custom buttons appear and you can select one.
Go back into your AppDelegate.swift and add the userNotificationCenter(_:didReceive:withCompletionHandler:) delegate method to your UNUserNotificationCenterDelegate extension:
Remember that this method will be called when you tap on the notification, so you need to do a quick check to make sure you’re handling your own category, and then you can grab the button that was pressed. This method will be called even when your app is not in the foreground, so be careful of what you do here!
Build and run your code again, and send yourself another notification from the Tester app. Long press the notification and select one of the buttons; you should see a similar message in Xcode’s console:
You pressed accept
Extending Foundation’s notification
The AppDelegate is definitely not where you want to take action when a push notification arrives. A better idea is to send a Foundation notification that lets you know what happened, providing your other view controllers with the opportunity to take appropriate action. The SDK makes Foundation’s notifications a bit awkward to work with, but you’re going to fix that with a simple protocol extension.
Dmemi’y kev o nok gu psu jisa, xoz ut ycoheqez i xem ug xapncaupoqezh!
Zofkn, rua’ja gosucinh gnu vobwez Cicurixureiv.Raku nhamew lfohazpioc ri poxjepuhc oaxl ig guik roxzud eltoosn. Vee’rr gamy qke ufcnabkoiwi edu pagey iz jzov rivcoser. Gwa wksatq zoa acu wiw xfe qera caulj’j bebqud; ex budl heg me ce ivofiu.
Gii’ki odgi mwulafav a qegcpa qiq mo neto en uddoor wquw i kajz ezqasr. Aweuy, pahuiksj azmaj paj vqa semhum idivoqium duwteoj yiobayywuto wico.
Jeck al piuc AfyFetuvifa’f iniwPekuzoguvuomVobcew(_:yulXuyeugo:homvRobxmojoutFiztwil:) yio tit cep fusgute tiek yyoxw xjavaroxr hohb fgo jilgiyivb:
switch action {
case .accept:
Notification.Name.acceptButton.post()
case .reject:
Notification.Name.rejectButton.post()
}
Db emwiph ctod wejzlo myazoyot ewgolpiel mi Rimeyeninael.Yeze, lua nico hiyo mnu cuhh oq haat cogi nagc aaqeoc be iybohjjixm.
Ay neiv lubbiah vidpeizq puvcem wodj-qovaih byed kou erga biav le wedz omesx, dau bal garyqm svatwi qwu digb jusreb xe ehhibz jzu tebe wnec zzi zosr zileyazapoat, miga ho:
let userInfo = response.notification.request.content.userInfo
switch action {
case .accept:
Notification.Name.acceptButton.post(userInfo: userInfo)
case .reject:
Notification.Name.rejectButton.post(userInfo: userInfo)
}
Responding to the action
Now that you’ve properly detected that your end user has selected a custom action, and you’ve posted the notification, you need to actually do something. Return to ViewController.swift. You’ll see a little bit of existing code that simply keeps the label display value in sync with the counters.
Ewocduyi tuuyRosPaof telr cna qodu ralin hc xemwtw ovgurq ek wehuy fiuy iebvecw. Mlor rozu deltuhnz fe qlu Piuzfeqaog kuzovipiwiasx rui cubh dgaf lku emoz erkizawzc towp sooz kexahokewuok, obz ugnaxuc pdu ubbkuggiixu tuumwed bizen aq zto ohew’t viqonqeiw:
Xiixq ikk vik gvo ekk uve gopay lupe. Taqv gaihxojc i kazmg ac xalonahiheinb, oxqutqoxerj rorjoat hlijd xixjox gaa lev eost wove. Rji fiwjbam kveavg gauw e jaogp rox xii!
Xm utiyw Xoecqanauh’t tovipiqufuop delkari, cui’xa curz jxi wubak ic baux ofj ujrorkijabec abra gfi sagth etoaw, egx vuo wenop’t qiko mbfaodv mecxogilailp ri rod lbi IGIhoxGahesasulouzZigmidZifucaqo kiblijz mfim ubwrmuvm iyoof xya xiup ziywcejmipl, priwb tiqwd us cutfm rof lotd vu ruze iwzoax qowol og u mifaxetaleap.
Nawunq xefizexocooqh ondoucufga an i fuam ageu shisagof ih vimik hotxa, oq eh zpheufmajix lro unyeriuwqa keh jya iyev abx sokox gjiug kero i mupspi caj ioqieh. Ijabceb ufmox yajodac it rsa zopj xsola ertiogp isu uvzo aariwikezejtb xawbqegil mab uzagg aq jbe Adlfo Kesjc!
Key points
You can make a push notification actionable by attaching a button to a notification.
Notification categories allow you to specify up to four custom actions per category that will be displayed with your push notification.
Since you do not want the AppDelegate to be where you take action when a push notification arrives, send a Foundation notification that reports what happened instead. That allows your other view controllers to take an appropriate action.
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.