How to cancel a local notification trigger in Swift
Asked Answered
K

2

8

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?

Kathrynekathy answered 24/3, 2019 at 14:15 Comment(5)
What did you mean by asking this? The system counts the active notifications only.Alyshaalysia
@Alyshaalysia 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?Kathrynekathy
Use the removePendingNotificationsWithIdentifier. You can cancel the notifications by given identifier.Alyshaalysia
@Alyshaalysia can u write that as an answer ? i'll give u the correct answerKathrynekathy
Possible duplicate of Delete a particular local notificationElectrotherapy
A
18

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”])
Alyshaalysia answered 24/3, 2019 at 14:46 Comment(0)
D
1

To build on top of Mannopson's answer:

This removes all pending Notifications (Swift 5)

func cancelNotifications() -> Void {
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
Detraction answered 5/5, 2020 at 11:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.