How to cancel UserNotifications
For cancelling all pending notifications, you can use this:
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
For cancelling specific notifications,
UNUserNotificationCenter.current().getPendingNotificationRequests { (notificationRequests) in
var identifiers: [String] = []
for notification:UNNotificationRequest in notificationRequests {
if notification.identifier == "identifierCancel" {
identifiers.append(notification.identifier)
}
}
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers)
}
The way same UNNotification
is identify are base on the identifier
passed when you create the UNNotificationRequest
.
In your example above,
let request = UNNotificationRequest(identifier: "myNotif", content: notif, trigger: dateTrigger)
You have actually hardcoded the identifier
to be "myNotif"
. This way, whenever you want to delete the already set notification you can do this:
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: "myNotif")
However, do take note that when you hardcode the identifier, every time when you add a request
to UNUserNotificationCenter
the notification is actually being replaced.
Example, if you scheduled a "myNotif"
request
set on 1 minute later but you call another function to schedule a "myNotif"
at 1 hour later it will be replaced. Therefore only the latest "myNotif"
at one hour later will be in the pendingNotificationRequest
.