We've been looking at the various improvements in Notifications in iOS 10, and today we're trying out one of the coolest new features: Notification Content Extensions. These allow us to display completely custom content when the user drags down or 3D Touches on one of our app's notifications. Let's dive in.

We'll start by adding a new target to our app and choosing Notification Content Extension.

We'll give it a name, and check out the files we get.

Like many of the other extension types we've covered, the whole thing is basically a view controller, storyboard, and Info.plist.

We'll head to the Info.plist first and configure a few things.

Since we want our custom content to be all that's visible once the users opens up our notification, we've added the UNNotificationExtensionDefaultContentHidden key hide the title and body text labels that are visible before open

We've also set our notification category to match the one we'll send in our UNNotificationContent.

Before we continue, let's add some actions to our notification so the user can actually do something about it. We've covered Notification Actions in the past (Bite #122), but here's how things work in the User Notifications Framework world:

// Somewhere before we request our first notification:
let evade = UNNotificationAction(
  identifier: "evade",
  title: "Evade with Autopilot 🤖"
)
let destroy = UNNotificationAction(
  identifier: "destroy",
  title: "Destroy (Weapons to Maximum!) ",
  options: [.destructive]
)
let category = UNNotificationCategory(
  identifier: "asteroid-detected",
  actions: [evade, destroy],
  intentIdentifiers: []
)

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

Now, we can configure a notification just like we have before:

let notification = UNMutableNotificationContent()

notification.categoryIdentifier = "asteroid-detected"

notification.title = "Asteroid Detected! 🚀"
notification.body = "Collision imminent. Immediate action required!"

Then we'll send off a request to the notification center to show the notification in 2 seconds. (Enough time for us to press the home button and head out to the home screen).

let request = UNNotificationRequest(
  identifier: "asteroid-id-123",
  content: notification,
  trigger: UNTimeIntervalNotificationTrigger(
    timeInterval: 2,
    repeats: false
  )
)

UNUserNotificationCenter.current().add(request)

Nice, so far so good. Now, let's see what happens when we open it up (either by 3D Touching on a supported device, or simply dragging down the banner):

Success! Our custom content is shown inside the notification, along with our custom actions.