Dismiss IOS Notification from NotificationContentExtention
Asked Answered
L

1

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()
}
Lutetium answered 25/6, 2020 at 22:27 Comment(2)
What's the difference between dismiss the NotificationContentExtension and dismissing the entire notification?Penuche
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)Lutetium
R
9

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.

Rabble answered 28/6, 2020 at 18:25 Comment(5)
Not exactly what I asked for, but it showed me the way. ThanksLutetium
@Lutetium What were you looking for? You didn't want it to be an action? You wanted it to be a normal button?Penuche
I wanted it to be a button inside the ContentExtension and I wanted to remove only that notification. Not all notifications on the notifications centerLutetium
@Lutetium You can use UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: <identifier>) to remove single notification.Rabble
@YardenST, I'm not able to dismiss exapaned notification. even with UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: <identifier>). Any other idea to remove expanded notification.Pretext

© 2022 - 2024 — McMap. All rights reserved.