iosswiftnotificationsnotification-content-extension

Dismiss IOS Notification from NotificationContentExtention


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()
}

Solution

  • 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.