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 in Context
To ask for authorization, get the shared
UNUser instance and call its
request method. Specify all of the interaction types that your app employs. For example, you can request 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.
Make the request in a context that helps the user to understand why your app needs authorization. For example, for a task-tracking app that sends reminder notifications, you could make the request after the user schedules a first task. This provides a better user experience than automatically requesting authorization on first launch, because the user can more easily see what purpose the notifications serve.
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, because 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 instance, the system doesn’t perform interactions if your app isn’t authorized to do so. To get the current settings, call the
get method of
The above example uses a guard condition to prevent the scheduling of notifications if the app isn’t 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 instance is set to
UNNotification. Your notification center delegate’s
user method also receives notifications when your app is in the foreground.