Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 303
Chief Madog Avatar asked Mar 24 '19 14:03

Chief Madog


People also ask

How does Swift handle local notifications?

The swift file (say ViewController. swift ) in which you want to create local notification should contain below code: //MARK: - Button functions func buttonIsPressed(sender: UIButton) { println("buttonIsPressed function called \(UIButton. description())") var localNotification = UILocalNotification() localNotification.

How do I use notifications in Swiftui?

If you run your app now, press the first button to request notification permission, then press the second to add an actual notification. Now for the important part: once your notification has been added press Cmd+L in the simulator to lock the screen.


1 Answers

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”])
like image 142
Mannopson Avatar answered Oct 09 '22 06:10

Mannopson