Apple推送通知操作按钮

时间:2017-09-18 15:54:21

标签: ios swift push-notification apple-push-notifications

我为我的应用设置了远程通知,其工作原理如下。 如果用户点击通知的正文,它会调用一个函数(将用户带到特定的ViewController)。 然而,当用户点击其中一个动作按钮时,按钮的动作与身体轻击动作一样执行。如何让动作按钮仅执行其动作,而身体也不会执行其动作。

这是我的代码示例:

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    completionHandler([.alert,.sound,.badge])
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    let userInfo = response.notification.request.content.userInfo as! [String:AnyHashable]

    // parse userInfo and execute a function in SWReveal to show the appropriate ViewController

    let action = response.actionIdentifier

    if action == "acceptFriendRequest" {
        print("Friend Request Accepted")
    }
}

func setCategories() {
    if #available(iOS 10.0, *) {
        let acceptFriendRequest = UNNotificationAction(
            identifier: "acceptFriendRequest",
            title: "Accept",
            options: [])
        let rejectFriendRequest = UNNotificationAction(identifier: "rejectFriendRequest", title: "Reject", options: [.destructive])
        let FrReq = UNNotificationCategory(
            identifier: "FrReq",
            actions: [acceptFriendRequest, rejectFriendRequest],
            intentIdentifiers: [],
            options: [.customDismissAction])}

1 个答案:

答案 0 :(得分:2)

我认为没有办法完全避免被调用的方法,因为它是委托方法。但是,函数开头的一个简单的guard语句应该做同样的技巧:

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    guard response.actionIdentifier != "acceptFriendRequest" && response.actionIdentifier != "rejectFriendRequest" else { return }

    let userInfo = response.notification.request.content.userInfo as! [String:AnyHashable]

    // parse userInfo and execute a function in SWReveal to show the appropriate ViewController

}

这样,如果动作标识符与任何一个动作相匹配,即按下了动作按钮,则不会执行该功能的其余部分。

相关问题