7

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Chief Madog
  • 1,738
  • 4
  • 28
  • 55
  • What did you mean by asking this? The system counts the active notifications only. – Mannopson Mar 24 '19 at 14:22
  • @Mannopson I ask, let's say I opened a trigger to show a local notification in 15 min, but after 10 minutes I want to cancel that trigger to not show the notification how do I do that? – Chief Madog Mar 24 '19 at 14:25
  • Use the `removePendingNotificationsWithIdentifier`. You can cancel the notifications by given identifier. – Mannopson Mar 24 '19 at 14:30
  • @Mannopson can u write that as an answer ? i'll give u the correct answer – Chief Madog Mar 24 '19 at 14:35
  • Possible duplicate of [Delete a particular local notification](https://stackoverflow.com/questions/6340664/delete-a-particular-local-notification) – Cœur Mar 24 '19 at 15:26

2 Answers2

16

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”])
Mannopson
  • 2,634
  • 1
  • 16
  • 32
-1

To build on top of Mannopson's answer:

This removes all pending Notifications (Swift 5)

func cancelNotifications() -> Void {
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
garytechy
  • 1
  • 2