将动态操作添加到UNNotificationCategory

时间:2017-12-19 16:28:30

标签: ios push-notification apple-push-notifications unusernotificationcenter notification-action

我目前面临的一个问题是,我需要能够根据通知发送的信息更改UNNotificationCategory的操作。目前我的类别设置与此类似:

func registerNotificationSettings(){
    let acceptAction = UNNotificationAction(identifier: "accept", title:  "accept", options: [])
    let denyAction = UNNotificationAction(identifier: "deny", title: "deny", options: [])

    let acceptCategory = UNNotificationCategory(identifier: "2", actions: [acceptAction], intentIdentifiers: [], options: [])
    let denyCategory = UNNotificationCategory(identifier: "1", actions: [denyAction], intentIdentifiers: [], options: [])

    let center = UNUserNotificationCenter.current()
    center.setNotificationCategories([acceptCategory, denyCategory])

    center.requestAuthorization(options: [.alert, .badge, .sound]){
       (granted, error) in
        if (granted){
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
}

此配置正常,但我需要能够根据用户设置更改每个类别的默认操作。例如,在“denyAction”中,“deny”可能需要更改为“reject”,或者在“acceptAction”中“accept”可能需要更改为“confirm”。这些是我们为用户在应用程序中指定自己的变量设置,我无法知道它们可能会改变它们。

目前我们有通知在每个通知的userInfo中发送“响应”词典,但我不知道如何在收到通知时更改通知操作。我发现的唯一文档提前设置了这些操作。有谁知道这是否可行?

1 个答案:

答案 0 :(得分:0)

我能够通过创建一个方法来解决这个问题,该方法从我的服务器请求可能的状态列表,其中包括与该状态相关的操作。然后我为每个状态创建一个UNNotificationCategory,为每个操作创建一个UNNotificationAction。我每次运行应用程序时都会调用此方法。这不是一个完美的解决方案,因为如果有人从不强制退出应用程序,并且状态数据发生变化,那么我就不会获得新数据。

以下是我的一些代码

for state in notificationStates {

            var notificationActions : [UNNotificationAction] = []
            for action in state.actions {
                let notificationAction = UNNotificationAction(identifier: action, title: action, options: [])
                notificationActions.append(notificationAction)
            }

            let muteAction = UNNotificationAction(identifier: "mute", title: "Mute", options: [])
            let commentAction = UNTextInputNotificationAction(identifier: "inline-comment", title: "Add Comment", options: [], textInputButtonTitle: "Add Comment", textInputPlaceholder: "Comment")

            notificationActions.append(muteAction)
            notificationActions.append(commentAction)

            let notificationCategory = UNNotificationCategory(identifier: state.id, actions: notificationActions, intentIdentifiers: [], options: [])
            notificationCategories.insert(notificationCategory)
        }
        center.setNotificationCategories(notificationCategories)