首页 > 解决方案 > 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])
}

我认为注意是错误的,但它不起作用。希望有人可以帮助我,我现在真的很困惑哈哈。

标签: iosswift

解决方案


您需要在调用 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"

这是拖动通知时的输出: 在此处输入图像描述


推荐阅读