UNNotificationAction按钮没有显示,为什么?

时间:2018-05-06 14:50:50

标签: ios swift

我引用了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])
}

我认为注意到错了,但这不行。希望有人可以帮助我,我现在真的很困惑大声笑。

1 个答案:

答案 0 :(得分:0)

您需要在调用 UNNotificationRequest 之前添加 content.categoryIdentifier =" COLOR_ACTION" ,如下面swift中的代码。

    //Set content
    let content = UNMutableNotificationContent()
    content.title = "Hello World"
    content.body = "My First Notification App"
    content.sound = UNNotificationSound.default()

    content.categoryIdentifier = "COLOR_ACTION"

以下是拖动通知时的输出: enter image description here