ios - UNNotificationAction 按钮未显示,为什么?
问题描述
我参考了 Apple 的代码,但不起作用,这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert,.sound]) { (granted, error) in
print(granted)
}
//Set content
let content = UNMutableNotificationContent()
content.title = "Hello World"
content.body = "My First Notification App"
content.sound = UNNotificationSound.default()
//Set trigger
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
//Set request
let uuid = UUID().uuidString
let request = UNNotificationRequest(identifier: uuid, content: content, trigger: trigger)
//Set actions
let blueAction = UNNotificationAction(identifier: "ACTION_BLUE", title: "Blue", options: .init(rawValue: 0))
let greenAction = UNNotificationAction(identifier: "ACTION_GREEN", title: "Green", options: .init(rawValue: 0))
let category = UNNotificationCategory(identifier: "COLOR_ACTION", actions: [blueAction,greenAction], intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "", options: .customDismissAction)
center.setNotificationCategories([category]) //category
center.add(request) { (err) in
if err != nil {
print(err)
}
}
// Do any additional setup after loading the view, typically from a nib.
}
这是 UNUserNotificationCenterDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.notification.request.content.categoryIdentifier == "COLOR_ACTION" {
}
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert,.sound])
}
我认为注意是错误的,但它不起作用。希望有人可以帮助我,我现在真的很困惑哈哈。
解决方案
您需要在调用 UNNotificationRequest 之前添加content.categoryIdentifier = "COLOR_ACTION" ,如下面的代码所示。
//Set content
let content = UNMutableNotificationContent()
content.title = "Hello World"
content.body = "My First Notification App"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "COLOR_ACTION"
推荐阅读
- php - 高负载会导致 PHP 无法写入文本文件吗?
- python - pymongo 在 insertmany 时忽略无效文档错误
- jenkins - 詹金斯工作在安静期间被取消仍然建立
- git - 将代码从 Gerrit 移动到 Github 时遇到“这超出了 GitHub 的文件大小限制 100.00 MB”的错误
- botframework - 自适应卡片提交操作中的样式
- python - 多标签分类 ML-kNN 与 KNN
- amazon-web-services - 使用 cloudformation 将弹性 IP 添加到 ec2 实例
- java - 为什么 Spring @Transactional 成功回滚(SQL 插入)但在(SQL 更新)时失败 - 多个数据源
- jquery - 如何使用缩小代码处理引导工具提示?
- android-studio - Flutter 内部版本号可以在 pubspec.yaml 文件之外维护吗