add(_:withCompletionHandler:)
Schedules the delivery of a local notification.
Declaration
func add(_ request: UNNotificationRequest, withCompletionHandler completionHandler: (@Sendable ((any Error)?) -> Void)? = nil)func add(_ request: UNNotificationRequest) async throwsParameters
- request:
The request object containing the notification payload and trigger information. This parameter must not be
nil. - completionHandler:
The block to execute with the results. This block may be executed on a background thread. The block has no return value and takes the following parameter:
- error
An error object indicating whether a problem occurred. If the notification was scheduled successfully, this parameter is
nil; otherwise, it is set to an error object indicating the reason for the failure.
Discussion
This method schedules local notifications only; you cannot use it to schedule the delivery of remote notifications. Upon calling this method, the system begins tracking the trigger conditions associated with your request. When the trigger condition is met, the system delivers your notification. If the request does not contain a UNNotificationTrigger object, the notification is delivered right away.
You may call this method from any thread of your app.
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "My notification title"
content.body = "My notification body"
let notification = UNNotificationRequest(identifier: "com.example.mynotification", content: content, trigger: nil)
do {
try await center.add(notification)
} catch {
// Handle any errors.
}