OGeek|极客世界-中国程序员成长平台

标题: ios - 向 UNNotificationCategory 添加动态操作 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:28
标题: ios - 向 UNNotificationCategory 添加动态操作

我目前面临一个问题,我需要能够根据随通知发送的信息更改 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 中都有发送“响应”字典的通知,但我不知道如何在收到通知时更改通知操作。我发现的唯一文档提前设置了这些操作。有谁知道这是否可能?



Best Answer-推荐答案


我能够通过创建一个方法来解决这个问题,该方法从我的服务器请求可能的状态列表,其中包括与该状态相关的操作。然后我为每个状态创建一个 UNNotificationCategory 并为每个 Action 创建一个 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)

关于ios - 向 UNNotificationCategory 添加动态操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47891203/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4