Topics

#122: Notification Actions 📢

Topics

Today we're going to look at how we can improve our app's notifications by adding actions to them. Notification Actions let our users perform a task directly inside the system's notification banner. Let's get started.

We'll be working in an imaginary Groceries app. The app currently notifies users when they're running low on something. We're going to make things even better by letting the user re-stock their pantry right from the notification banner.

First, we'll create a couple of UIMutableUserNotificationActions:

let reorderAction = UIMutableUserNotificationAction()
reorderAction.title = "Order More"
reorderAction.identifier = "com.groceries.running-low.reorder"
reorderAction.authenticationRequired = false
reorderAction.activationMode = .Background

let remindLaterAction = UIMutableUserNotificationAction()
remindLaterAction.title = "Remind Me Later"
remindLaterAction.identifier = "com.groceries.running-low.postpone"
remindLaterAction.authenticationRequired = false
remindLaterAction.activationMode = .Background

These action objects describe the buttons the user will see when they expand the notification banner after it appears.

Next, we'll attach these actions to a notification category, then pass that category in when we register for user notifications:

let category = UIMutableUserNotificationCategory()
category.identifier = "com.groceries.running-low"
category.setActions([reorderAction, remindLaterAction], 
  forContext: .Default)

application.registerUserNotificationSettings(
  UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge],
    categories: [category]))

Finally, we'll implement a delegate function to handle our actions:

func application(
  application: UIApplication, 
  handleActionWithIdentifier identifier: String?,
  forRemoteNotification userInfo: [NSObject : AnyObject], 
  withResponseInfo responseInfo: [NSObject : AnyObject],
  completionHandler: () -> Void
) {
  // handle the action, based on its identifier
  completionHandler()
}