6

Is it possible to dismiss/cancel a local notification from a button with in NotificationContentExtension?

I was only able to dismiss the NotificationContentExtension itself, but not the entire notification.

if #available(iOSApplicationExtension 12.0, *) {
          self.extensionContext?.dismissNotificationContentExtension()
}
YardenST
  • 5,119
  • 2
  • 33
  • 54
  • What's the difference between _dismiss the `NotificationContentExtension`_ and _dismissing the entire notification_? – mfaani Jun 28 '20 at 16:04
  • dismissing a notification removes it from the lock screen altogether. Dismissing the content extension undo the long press effect (which shows the buttons or custom GUI) – YardenST Jun 28 '20 at 17:41

1 Answers1

8

You can do it using UNUserNotificationCenter & UNNotificationContentExtension protocol

Add action using UNUserNotificationCenter

let center = UNUserNotificationCenter.current()
center.delegate = self  
center.requestAuthorization (options: [.alert, .sound]) {(_, _) in 
}  
let clearAction = UNNotificationAction(identifier: "ClearNotif", title: "Clear", options: [])
let category = UNNotificationCategory(identifier: "ClearNotifCategory", actions: [clearAction], intentIdentifiers: [], options: [])
 center.setNotificationCategories([category])

Add a delegate method of the protocol UNNotificationContentExtension in your extension's view controller

 func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
    if response.actionIdentifier == "ClearNotif" {
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    }
    completion(.dismiss)
}

Try it and let me know it works.

Shashank Mishra
  • 1,051
  • 7
  • 18
  • 1
    Not exactly what I asked for, but it showed me the way. Thanks – YardenST Jun 29 '20 at 16:49
  • @YardenST What were you looking for? You didn't want it to be an action? You wanted it to be a normal button? – mfaani Jun 29 '20 at 18:55
  • 1
    I wanted it to be a button inside the ContentExtension and I wanted to remove only that notification. Not all notifications on the notifications center – YardenST Jun 30 '20 at 05:33
  • @YardenST You can use UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ) to remove single notification. – Shashank Mishra Jun 30 '20 at 06:06
  • 1
    @YardenST, I'm not able to dismiss exapaned notification. even with UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ). Any other idea to remove expanded notification. – rv7284 Dec 11 '20 at 05:01