Create and schedule notifications from your app when you want to get the user's attention.
Use local notifications to get the user's attention. You can display an alert, play a sound, or badge your app's icon. For example, a background app could ask the system to display an alert when a particular task is finished. Always use local notifications to convey important information that the user wants.
The delivery of notifications is handled by the system, based on a time or location that you specify. If the delivery of the notification occurs when your app is not running or in the background, the system interacts with the user for you. If your app is in the foreground, the system delivers the notification to your app for handling.
Create the Notification's Content
Fill in the properties of a
UNMutable object with the details of your notification. The fields you fill in define how your notification is delivered. For example, to play a sound, assign a value to the
sound property of the object. Listing 1 shows a content object that displays an alert containing a title string and body text. You can specify multiple types of interaction in the same request.
Specify the Conditions for Delivery
Specify the conditions for delivering your notification using a
UNLocation object. Each trigger object requires different parameters. For example, a calendar-based trigger requires you to specify the date and time of delivery.
Listing 2 shows you how to configure a notification to be delivered every Tuesday at 2pm. The
Date structure specifies the timing for the event. Configuring the trigger with the
repeats parameter set to
true causes the system to reschedule the event after its delivery.
Create and Register a Notification Request
UNNotification object that includes your content and trigger conditions, and call the
add(_: method to schedule your request with the system. Listing 3 shows an example that uses the content from Listing 1 and Listing 2 to fill in the request object.
Cancel a Scheduled Notification Request
Once scheduled, a notification request remains active until its trigger condition is met, or you explicitly cancel it. Typically, you cancel a request when conditions change and you no longer need to notify the user. For example, if the user completes a reminder, you would cancel any active requests associated with that reminder. To cancel an active notification request, call the
remove method of