ios - 从 NotificationContentExtention 关闭 IOS 通知

标签 ios swift notifications notification-content-extension

是否可以通过 NotificationContentExtension 中的按钮关闭/取消本地通知?
我只能关闭 NotificationContentExtension 本身,但不能关闭整个通知。

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

最佳答案

您可以使用 UNUserNotificationCenter 和 UNNotificationContentExtension 协议(protocol)来完成
使用 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])
在扩展的 View Controller 中添加协议(protocol) UNNotificationContentExtension 的委托(delegate)方法
 func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) {
    if response.actionIdentifier == "ClearNotif" {
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    }
    completion(.dismiss)
}
试试看,让我知道它有效。

关于ios - 从 NotificationContentExtention 关闭 IOS 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62585251/

相关文章:

ios - Swift - 当收到无声通知时决定是否显示警报

php - 一个类似 facebook 的 php 通知系统

android - 通知 channel 的重要性是否会被个别通知的重要性所覆盖?

ios - YTPlayerView(youTube)付款者未在iOS 11中播放视频

ios - 如何将图像文字添加到数组并显示它们?

Swift 4 UILabel 动画颜色

arrays - Swift 中的数组可变性追加

使用 UIWebView 或任何替代方法与 webRTC 进行 iOS 视频/音频通话

android - 可以从工作线程调用 NotificationManager.notify() 吗?

ios - CoreData 迁移问题