I have seen several threads on this here and elsewhere but none seem to be using the new UserNotifications
framework for iOS 10
There is an instance method getDeliveredNotifications(completionHandler:)
that is called on UNUserNotificationCenter
singleton function current()
The completionHandler:
takes an array of delivered notifications that could then be removed inside the block using removeDeliveredNotifications(withIdentifiers:)
UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
// UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [String])
}
My challenge is how to identify a specific notification from all delivered notifications and then remove it?
This is what I am doing right now to see if there is a remote notification delivered with the id I had sent from the server with the payload key ID
. This doesn't remove the notification in question, obviously because the first function returns nil although the notification is visible in the notification center.
func isThereANotificationForID(_ ID: Int) -> UNNotification? {
var foundNotification: UNNotification?
UNUserNotificationCenter.current().getDeliveredNotifications {
DispatchQueue.main.async {
for notification in notifications {
if notification.request.content.userInfo["id"] as! Int == ID {
foundNotification = notification
}
}
}
}
return foundNotification
}
func removeNotification(_ notification: UNNotification) {
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [notification.request.identifier])
}
// Find the notification and remove it
if let deliveredNotification = isThereANotificationForID(ID) {
removeNotification(deliveredNotification)
}