在 运行 时间更改交互式通知中的操作标题

Changing action titles in interactive notifications at run time

根据我的理解,我必须在其中为本地或远程交互式通知注册类别和操作,现在我的要求是我想显示带有动态标题的按钮作为推送负载的一部分。

作为替代方案,我还尝试了在收到远程通知时使用已注册设置触发本地通知的选项,但不知何故它不起作用,本地通知未触发。非常感谢帮助。

简短的回答是您无法在运行时更改操作按钮标题。

但是,您可以尝试以下操作:

  1. 在向设备发送通知之前,使用 content-available 属性 向其发送 "silent" 通知。在此通知中,发送代表您的新操作按钮标题的数据。

  2. 使用registerUserNotificationSettings:更新您的相关类别。

  3. 发送带有您刚刚创建的新操作标题的 "real" 通知。

它需要测试,因为我从未在生产模式下尝试过。另外,请考虑到您要将发送的通知数量加倍。

如@Asaf 所述,需要使用 registerUserNotificationSettings 重新注册相关类别:

只需使用以下代码即可实现:

 let actionAnswer  = UserNotificationAction(title: kAnswerEventTitle, identifier: kAnswerEventIdentitfier, activationMode: .Foreground, authenticationRequired: false, isDestructive: false)
        let actionReject  = UserNotificationAction(title: kRejectEventTitle, identifier: kRejectEventIdentitfier, activationMode: .Background, authenticationRequired: false, isDestructive: true)
registerModiifedUserNotificationCategory(userActions)

//For Notification Actions - object
struct UserNotificationAction {
    var title: String
    var identifier: String
    var activationMode: UIUserNotificationActivationMode
    var authenticationRequired: Bool
    var isDestructive:Bool

    init(title: String, identifier: String, activationMode: UIUserNotificationActivationMode? = .Background, authenticationRequired: Bool? = false, isDestructive: Bool? = false){
        self.title = title
        self.identifier = identifier
        self.activationMode = activationMode!
        self.authenticationRequired = authenticationRequired!
        self.isDestructive = isDestructive!
    }
}


  //func for dynamic UIMutableUserNotificationCategory and UIMutableUserNotificationAction creation
    func createCategoryUserNotification(notificationActions: [UserNotificationAction]) -> UIMutableUserNotificationCategory {

        var UserNotificationActions = [UIMutableUserNotificationAction]()

        for userAction in notificationActions {
            let actionItem = UIMutableUserNotificationAction()
            actionItem.activationMode = userAction.activationMode
            actionItem.title = userAction.title
            actionItem.identifier = userAction.identifier
            actionItem.destructive = userAction.isDestructive
            actionItem.authenticationRequired = userAction.authenticationRequired
            UserNotificationActions.append(actionItem)
        }

        var runTimeCategoryUserNotification: UIMutableUserNotificationCategory{
            let userCategory = UIMutableUserNotificationCategory()
            userCategory.identifier = getGenericCategoryIdentifier(notificationActions)
            userCategory.setActions(UserNotificationActions, forContext:.Default)
            return userCategory
        }
        return runTimeCategoryUserNotification
    }

 //Re-Registering USer notification, if any new Categories required
    func registerModiifedUserNotificationCategory( notificationActions: [UserNotificationAction])-> Bool {

        // let UwerNotification = UserNotificationActions()
        let newCategory = createCategoryUserNotification(notificationActions)

        let settings = UIApplication.sharedApplication().currentUserNotificationSettings()

        if settings!.types == .None {
            return false
        }

        let oldUserNotificationsettings = UIApplication.sharedApplication().currentUserNotificationSettings()

        var newCategories:[UIMutableUserNotificationCategory] = [UIMutableUserNotificationCategory]()
        var isNewCategoryFoundInExist: Bool = false

        for category in (oldUserNotificationsettings?.categories)! {
            if category.identifier == newCategory.identifier{
                isNewCategoryFoundInExist = true
            }

            if category.identifier ==  kGeneralCategoryUserNotification{//if any predefined Categories
                newCategories.append(generalCategoryUserNotification)

            }else if category.identifier ==  kCallCategoryUserNotification{//if any predefined Categories
                newCategories.append(callCategoryUserNotififation)

            }/* else{// some XYZ Category registered at runtime and if still want to Re-register
             let actions = category.actionsForContext(.Default)
             print(category.actionsForContext(.Default))

             if actions?.count > 0 {
             var genericCategoryUserNotififation: UIMutableUserNotificationCategory{
             let userCategory = UIMutableUserNotificationCategory()
             userCategory.identifier = UwerNotification.getGenericCategoryIdentifierFromUserNotifAction(actions!)
             userCategory.setActions(actions, forContext:.Default)
             return userCategory
             }
             newCategories.append(genericCategoryUserNotififation )
             }
             }*/

        }

        //REgister with new category of Notification if any
        if !isNewCategoryFoundInExist {
            newCategories.append(newCategory)


                var categories =  Set<UIUserNotificationCategory>()
                for categr in newCategories{
                    categories.insert(categr)
                }
                let settings =  UIUserNotificationSettings(forTypes:[.Alert, .Badge, .Sound], categories: categories)

               //Register here registerUserNotificationSettings
        }

        return true

    }


    // generic Category Identifer based on concat of Action Identifiers
    func getGenericCategoryIdentifier(notificationActions: [UserNotificationAction]) -> String {
        let  actionIdentifiers = notificationActions.map({[=11=].identifier})
        let genericCategoryIdentifier = actionIdentifiers.joinWithSeparator("")
        return genericCategoryIdentifier
    } 

对于正在寻找此问题解决方案的人

1.Create 通知服务扩展

  1. 在 didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler

创建操作按钮并将类别再次注册到通知中心

例如:

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    NSDictionary * userInfo = request.content.userInfo;
NSArray * actionButtons = [userInfo valueForKeyPath:@"payload.actionButton"];

 if(actionButtons){

    NSMutableArray * buttons = [NSMutableArray new];

    for(NSDictionary * actionButton in actionButtons){

        UNNotificationAction *ActionBtn = [UNNotificationAction actionWithIdentifier:[actionButton valueForKey:@"actionDeeplink"] title:[actionButton valueForKey:@"actionName"] options:UNNotificationActionOptionNone];
        [buttons addObject:ActionBtn];

    }

    UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"myNotificationCategory" actions:buttons intentIdentifiers:@[] options:UNNotificationCategoryOptionNone];

    NSSet *categories = [NSSet setWithObject:category];

    [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:categories];

  }

}

然后在您的通知负载中执行如下操作:

    {
    "aps" : {
        "alert" : {
        "title" : "Manish Malviya",
        "body" : "iOS Developer"
        },
        "mutable-content" : 1,
    "content-available" : 1,
        "category" : "myNotificationCategory"
    },
    "payload" : {"actionButton": [
      {
        "actionName": "Yes",
        "actionDeeplink": "nottest"
      },
      {
        "actionName": "May be",
        "actionDeeplink": "tes"
      },
      {
        "actionName": "No",
        "actionDeeplink": "test"
      }
    ]
    }
 }

瞧瞧输出。