关闭来自 NotificationContentExtention 的 IOS 通知

Dismiss IOS Notification from NotificationContentExtention

是否有可能 dismiss/cancel 来自带有 NotificationContentExtension 的按钮的本地通知?

我只能关闭 NotificationContentExtension 本身,但不能关闭整个通知。

if #available(iOSApplicationExtension 12.0, *) {
          self.extensionContext?.dismissNotificationContentExtension()
}

您可以使用 UNUserNotificationCenter 和 UNNotificationContentExtension 协议来做到这一点

使用 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])

在您的扩展的视图控制器中添加协议 UNNotificationContentExtension 的委托方法

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

尝试一下,让我知道它有效。