Notifications are a huge part of making our apps useful. They allow us to notify the user both actively and passively of important information, providing the immediacy users have come to expect.
In iOS 10, Apple has overhauled how notifications work. Today we'll begin looking at these changes with the new User Notifications framework. Let's dive in. 🏊
It all starts with UNUserNotificationCenter
, and more specifically:
UNUserNotificationCenter.current()
We'll use the current notification center to authorize, schedule, retrieve, and generally manage the notifications our app displays.
Before we can do anything, we'll need to ask for permission. We can pass in some options for the kinds of notification behaviors we'd like permission to use:
UNUserNotificationCenter.current()
.requestAuthorization(
options: [.badge, .sound, .alert, .carPlay]
) { granted, error in
if granted {
// yay!
}
}
For the next step, we'll return to our imaginary Spaceships application. Let's say we have a feature that alerts the user when an asteroid is detected in our path.
To show a notification to the user about the space rock, we'll need to create a new UNNotificationRequest
and add it to the notification center.
We'll start by creating a UNMutableNotificationContent
and configuring it for our needs:
let notification = UNMutableNotificationContent()
notification.categoryIdentifier = "asteroid-detected"
notification.title = "Asteroid Detected! 🚀"
notification.body = "Collision imminent. Immediate action required!"
The categoryIdentifier
here is simply a unique string we create. Later, we'll use this to identify "Asteroid Detected" notifications and differentiate them amongst from other kinds of notifications our app might display.
Next, we'll actually create the notification request:
let request = UNNotificationRequest(
identifier: "asteroid-id-123",
content: notification,
trigger: nil
)
We haven't specified a trigger here, which tells the system we'd like this notification to be shown right away.
Finally, we'll add the request to the notification center:
UNUserNotificationCenter.current().add(request)
We'll wrap all this in a quick function and call it with a 2 second delay so we have time to press the home button and get to the home screen to see the notification appear.
import Dispatch
func applicationDidBecomeActive(_ application: UIApplication) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2)) {
showTestNotification()
}
}
Success!