Adding actions to notifications

When you implemented the code to handle incoming notifications, you implemented a method called userNotificationCenter(_:didReceive:withCompletionHandler:). This method contains information about the way the user chose to handle the notification. The could have tapped on the notification itself, which is the default action, or maybe they chose one of the custom actions that are associated with the notification by swiping it. Another way for users to make custom notifications appear is to 3D-Touch on it.

There are three main kinds of actions supported by notifications. The first is a background action. Background actions dismiss the notification and wake the app in the background, so it can take appropriate measures for the selected action. An example of this is accepting a calendar invite through an action. If a user accepts or declines an invite inside the notification, they don't have to be taken to the app, because the response can be handled in the background just fine.

The second type of action is a foreground action. A foreground action takes the user into the app that sent the notification. It's up to the app to handle the selected action in a way that makes sense.

Lastly, you can add text input actions to your notifications. These types of actions are basically background actions, except they take user input. A text input action is great if you're building a messaging app.

All notification actions are associated with a notification category. These categories must be registered on the Notification Center at app launch. Again, the perfect place to set this up is application(_:didFinishLaunchingWithOptions:). Add the following code to this method to configure a notification action that allows a user to mark one of their reminders as completed:

let completeAction = UNNotificationAction(identifier: "complete-reminder", title: "Complete", options: [])

let reminderCategory = UNNotificationCategory(identifier: "reminder", actions: [completeAction], intentIdentifiers: [], options: [])

UNUserNotificationCenter.current().setNotificationCategories([reminderCategory])

The preceding code creates a custom action that is attached to the reminder category. The default behavior for a notification is to handle actions in the background. If you want an action to take the user into your app, you need to add the .foreground option to the options parameter for the action. Lastly, the new category is added to the Notification Center.

Associating a category with a notification is done through the categoryIdentifier property of UNNotificationContent. Add the following line of code to the createNotificationContentForReminder(_:) method in NotificationsHelper.swift to add the reminder category to the notifications that are scheduled by the app:

content.categoryIdentifier = "reminder"

If you 3D-Touch the notifications that is sent by the app now, you're presented with a custom action:

When the user taps on this action, userNotificationCenter(_:didReceive:) is called to notify your app about the fact that the user tapped on your custom action. Add the following implementation for this method to AppDelegate.swift to mark a reminder as completed when the user selects the Complete action:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

  let userInfo = response.notification.request.content.userInfo

  guard response.actionIdentifier == "complete-reminder",
    let identifier = userInfo["reminder-uuid"] as? String else {
      completionHandler()
      return
  }

  let fetchRequest: NSFetchRequest<Reminder> = Reminder.fetchRequest()
  fetchRequest.predicate = NSPredicate(format: "identifier == %@", identifier)

  let moc = PersistentHelper.persistentContainer.viewContext
  guard let results = try? moc.fetch(fetchRequest),
    let reminder = results.first else {
      completionHandler()
      return
  }

  moc.perform {
    reminder.isCompleted = true
    try! moc.save()

    completionHandler()
  }
}

The preceding code extracts all relevant information from the notification response and uses it to find a reminder that matches the identifier that was added to the notification's userInfo dictionary. If a reminder was found, it's marked as completed and the managed object context is saved to persist the new reminder status.

Notification actions are a great way to add quick interactions to your notifications, and they are already a huge improvement over simply sending a plain notification. Another way to make great improvements to the way you send notifications to your users is to implement the new notification grouping that was introduced in iOS 12.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset