How to set local alerts using UNNotificationCenter

Local notifications are messages that appear on the user's lock screen when your app isn't running. The user can then swipe to unlock their device and go straight to your app, at which point you can act on the notification.

All this is done using the User Notifications framework, so import that now:

import UserNotifications

To begin with, you need to ask for permission in order to show messages on the lock screen. Here's how that's done:

That will show an alert to the user asking them if they want to let you show notifications. When it comes to scheduling a notification, you need to choose a trigger (when to show) and content (what to show), then combine them together into a single request.

That will show an alert at 10:30am every day, because its repeats property is set to true.

The notification request code above also set a userInfo property on the notification, which is a dictionary where you can store any kind of context data you want. This dictionary gets given back to you when the user unlocks their device using your notification, so you can act on the alert in a meaningful way.

If you want to attach custom buttons to your notification, you need to use the UNNotificationAction class, then register various actions against a category string. We used the category identifier string of “alarm” above, so we could attach a button to that category like this:

When a message comes in, your delegate will get notified and you can take the appropriate action. We gave the “Tell me more…” button the identifier “show”, so that’s what will be passed to us if the user taps that button. Alternatively, we’ll be sent UNNotificationDefaultActionIdentifier to mean “the user swiped to unlock using our notification.”