Ask the user's permission to display alerts, play sounds, or badge the app’s icon in response to a notification.
Local and remote notifications get the user’s attention by displaying an alert, badging your app’s icon, or playing sounds. These interactions occur when your app isn't running or is in the background. They let users know that your app has relevant information for them to view. Because the user might consider notification-based interactions disruptive, you must obtain permission to use them.
Request Authorization at Launch Time
Make your authorization request during your app's launch cycle. In your app's launch-time code, get the shared
UNUser object and call its
request method, as shown in Listing 1. Specify all of the interaction types that your app employs. The example requests authorization to display alerts and play sounds.
The first time your app makes this authorization request, the system prompts the user to grant or deny the request and records the user’s response. Subsequent authorization requests don't prompt the user.
Configure Notification Support Based on Authorized Interactions
Before trying to schedule local notifications from your app, make sure that your app is authorized to do so. Even if permission was granted initially, the user can change your app’s authorization settings at any time. Users can also change the types of interactions that are allowed for your app, which might cause you to change the way you configure your notifications.
Use authorization settings to provide a better experience for your users. Even if you specify the appropriate information in your
UNMutable object, the system doesn't perform interactions if your app is not authorized to do so. To get the current settings, call the
get method of
UNUser. In Listing 2, the code determines uses a guard condition to prevent the scheduling of notifications if the app is not authorized. The code then configures the notification based on what types of interactions are allowed, preferring the use of an alert-based notification whenever possible.
Even if your app isn't authorized for specific interactions, you may want to configure your notification with the relevant information anyway. Notifications containing alerts are still displayed in Notification Center if the
notification property of the
UNNotification object is set to
UNNotification. Notifications are also delivered to the
user method of your notification center delegate when your app is in the foreground.