nelson PARRILLA
nelson PARRILLA

Reputation: 703

How to stop UNUserNotificationCenter using UNTimeIntervalNotificationTrigger in Swift 5?

I have an UNUserNotificationCenter that send local notification every 60 secondes. It is implemented like below:

    let userNotificationCenter = UNUserNotificationCenter.current()
    let notificationContent = UNMutableNotificationContent()
    notificationContent.title = "Test title"
    notificationContent.body = "Test body"

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60,
                                                    repeats: true)

    let request = UNNotificationRequest(identifier: "testNotification",
                                        content: notificationContent,
                                        trigger: trigger)

    userNotificationCenter.add(request) { (error) in
        if let error = error {
            print("Notification Error: ", error)
        }
    }

It works well but I can't stop it and it continues to send notifications even if my app is killed.

What is the best way to stop UNUserNotificationCenter to send notifications in this case ?

Upvotes: 0

Views: 696

Answers (1)

David Pasztor
David Pasztor

Reputation: 54785

You simply need to call removePendingNotificationRequests(withIdentifiers:) and pass in the identifiers for which you need to cancel the scheduled, but undelivered notifications.

userNotificationCenter.removePendingNotificationRequests(withIdentifiers: ["testNotification"])

Or if you want to remove all pending notifications for your app, you can call removeAllPendingNotificationRequests() instead.

Upvotes: 2

Related Questions