swiftunusernotificationcenterunnotificationrequest

How to cancel a local notification trigger in Swift


I have a trigger to show a notification to the user:

let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Body"
content.sound = UNNotificationSound.default

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 20, repeats: false)

let request = UNNotificationRequest(identifier: "TestIdentifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

Is there a way for me to cancel that trigger once it has been set?

How do I cancel the notification before the timeInterval runs out and call the notification?


Solution

  • You can cancel or remove notifications by calling:

    let center = UNUserNotificationCenter.current()
    

    Remove pending notifications with given identifier

    center.removePendingNotificationRequests(withIdentifiers: [“givenIdentifier”])
    

    And remove delivered notifications with given identifier

    center.removeDeliveredNotifications(withIdentifiers: [“givenIdentifier”])