Class

UNUserNotificationCenter

The central object for managing notification-related activities for your app or app extension.

Overview

You use the shared UNUserNotificationCenter object to schedule notifications and manage notification-related behaviors in your app or app extension. The shared user notification center object supports both local or remote notifications in varying capacities. Use this object to perform the following types of tasks:

  • Request authorization for displaying alerts, playing sounds, or badging the app’s icon in response to local or remote notifications. (Authorization is required for all user interactions.)

  • Declare the notification types that your app supports and the custom actions (if any) that the user may perform when those notifications are delivered.

  • Schedule the delivery of notifications from your app.

  • Manage app-specific notifications displayed in Notification Center.

  • Get the notification-related settings for your app.

The notifications that you schedule directly from your app are known as local notifications because your app creates them locally on the user’s device. By contrast, remote notifications are created by your own server and delivered to the user’s device via the Apple Push Notification Service (APNS). For more information about local and remote notifications, see Local and Remote Notification Programming Guide.

Requesting Authorization for User Interactions

Requesting authorization is required of all apps that support the delivery of notifications. You request authorization using the requestAuthorization(options:completionHandler:) method, which you typically call early in your executable’s life cycle. The first time your app requests authorization, the user is alerted and given an opportunity to deny or grant that authorization. After the initial request, the system remembers the user’s response and returns it during subsequent requests. You must request authorization for both local and remote notifications.

Listing 1 shows how to request authorization to play sounds and display alerts. Use the completion handler block to take action following the acceptance or denial of the services.

Listing 1

Requesting authorization for user interactions

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
    // Enable or disable features based on authorization
}

The user can change the authorized settings for your app at any time using system settings. If you request a notification that contains a type of interaction for which your app is not authorized, the system delivers the notification without that specific interaction. To get your app’s current notification settings, call the getNotificationSettings(completionHandler:) method.

Configuring Actionable Notifications Using Categories

Actionable notifications give you a way to associate custom actions with your notifications. Normally, the user can only dismiss notification alerts. With actionable notifications, you can instruct the system to add custom buttons that give the user additional ways to respond to the notification. For example, a calendar program that sends a notification for a meeting invitation might define buttons to accept or decline the invitation. These extra buttons let the user perform common tasks more quickly and without launching the app.

To implement support for actionable notifications, do the following:

  1. Declare the notification categories that your app supports using the setNotificationCategories(_:) method.

  2. When creating local or remote notifications, include the appropriate category identifier string in the notification’s content:

    • For local notifications, assign this string to the categoryIdentifier property of the content object.

    • For remote notifications, assign the string to the category attribute of the notification payload.

  3. Handle user-selected actions by implementing the userNotificationCenter(_:didReceive:withCompletionHandler:) method of the notification center delegate.

For more information about defining categories for your notifications, see UNNotificationCategory.

Scheduling Notifications Locally

You schedule local notifications by creating a UNNotificationRequest object and passing it to the add(_:withCompletionHandler:) method of the shared user notification center. A notification request includes the content of the notification and the condition that triggers the delivery of the notification. The notification’s content includes the details of how you want to alert the user. For example, you might include text to display in an alert message, an updated badge value for the user’s app, or a sound to play. Listing 2 shows how to configure the notification request object and schedule it. The notification in the example is delivered five seconds after it is scheduled.

Listing 2

Scheduling a local notification

let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: 
               "Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: 
               "Hello_message_body", arguments: nil)

// Deliver the notification in five seconds.
content.sound = UNNotificationSound.default() 
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, 
            repeats: false)

// Schedule the notification.
let request = UNNotificationRequest(identifier: "FiveSecond", content: content, trigger: trigger) 
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: nil)

Because you normally schedule notifications to be delivered at a future time, you can cancel notifications before they are delivered using the removePendingNotificationRequests(withIdentifiers:) or removeAllPendingNotificationRequests() methods. These methods work only for notifications you schedule locally on the user’s device. The cancellation of remote notifications must happen on the server that originates those notifications.

Using a Delegate to Manage Notifications

Some notification-related tasks require you to assign a delegate object to the shared user notification center object. The delegate object is an object that adopts the UNUserNotificationCenterDelegate protocol. You use this object to perform the following tasks:

  • Determine whether to display the system notification interface when your app is in the foreground.

  • Respond when the user selects one of your app’s custom actions.

For more information about implementing the delegate, see UNUserNotificationCenterDelegate.

Thread-Safety Information

You may use the shared user notification center object from any thread of your app. However, you should use this object from only one thread at a time. Do not try to use it from multiple threads simultaneously. Always assign your delegate object to the shared user notification center's delegate property before using the object. It is a programmer error to assign a delegate after calling methods that might return information to that delegate.

Topics

Getting the Notification Center

class func current()

Returns the singleton user notification center object for your app or app extension.

Receiving Notifications and Handling Actions

var delegate: UNUserNotificationCenterDelegate?

The delegate used to process delivered notifications.

protocol UNUserNotificationCenterDelegate

The interface for handling notification-related interactions in your app or app extension.

Managing Settings and Authorization

func requestAuthorization(options: UNAuthorizationOptions = [], completionHandler: (Bool, Error?) -> Void)

Requests authorization to interact with the user when local and remote notifications arrive.

var supportsContentExtensions: Bool

A Boolean value indicating whether the current device supports content extensions.

Managing the Notification Categories

func setNotificationCategories(Set<UNNotificationCategory>)

Registers your app’s notification types and the custom actions that they support.

func getNotificationCategories(completionHandler: (Set<UNNotificationCategory>) -> Void)

Retrieves the app’s currently registered notification categories.

Managing Notification Requests

func getPendingNotificationRequests(completionHandler: ([UNNotificationRequest]) -> Void)

Returns a list of all notification requests that are scheduled and waiting to be delivered.

func removePendingNotificationRequests(withIdentifiers: [String])

Unschedules the specified notification requests.

func removeAllPendingNotificationRequests()

Unschedules all pending notification requests.

Managing Delivered Notifications

func getDeliveredNotifications(completionHandler: ([UNNotification]) -> Void)

Provides you with a list of the app’s notifications that are still displayed in Notification Center.

func removeDeliveredNotifications(withIdentifiers: [String])

Removes the specified notifications from Notification Center.

func removeAllDeliveredNotifications()

Removes all of the app’s notifications from Notification Center.

Constants

struct UNAuthorizationOptions

Constants for requesting authorization to interact with the user.

Error Domain

The error domain for notifications.

let UNErrorDomain: String

The error domain for notifications.

Relationships

Inherits From

Conforms To

See Also

First Steps

protocol UNUserNotificationCenterDelegate

The interface for handling notification-related interactions in your app or app extension.

class UNNotificationSettings

The object for managing notification-related settings and the authorization status of your app