获得初始权限后,是否可以向UIUserNotificationCategory添加新操作?

时间:2015-09-07 00:33:43

标签: ios swift notifications ios9

背景

问题

在iOS 9发布后,我希望“升级”我的用户并支持推送通知中的这个新的“在线回复”选项...但显然我首先需要添加每个用户UIMutableUserNotificationAction

的新UIApplication.sharedApplication().currentUserNotificationSettings()(带有新的行为属性)

问题

由于我已拥有一般通知权限(徽章/声音/提醒),我可以,安静地重新执行UIApplication.sharedApplication().registerUserNotificationSettings并添加新的“在线回复”操作吗?

1 个答案:

答案 0 :(得分:0)

事实证明,你不能简单地拨打UIApplication.sharedApplication().registerUserNotificationSettings并添加一个新动作 - 这样做只会注册 单个新动作(并吹掉所有其他动作)

以下是我最终在application: didFinishLaunchingWithOptions中所做的事情:

注意:我使用count < 2的逻辑检查,因为在我的应用程序的先前版本中,我只在目标类别中建立了一个操作(“REPLY_CATEGORY”)。

// This code ensures that iOS 9 Users (especially iOS 8 ==> iOS 9 upgraders) will be able to see
//  iOS 9's new text input 'behavior', available for notifications quick-actions
if #available(iOS 9, *) {
  if NSUserDefaults.standardUserDefaults().boolForKey("asked_for_notification_permission") {
    let settings: UIUserNotificationSettings = UIApplication.sharedApplication().currentUserNotificationSettings()!

    for category in settings.categories! {
      let cat: UIUserNotificationCategory = category 
      if cat.identifier == "REPLY_CATEGORY" {
        if cat.actionsForContext(UIUserNotificationActionContext.Default)!.count < 2 {
          print("! aD: iOS 9 User has less than the expected reply actions")

          // Re-build entire categories / actions here, including
          //   the new action with .behavior = .TextInput
          // THEN, simply re-register:

          let notificationCategories = NSSet(array: allCategories)
          let settings: UIUserNotificationType = [.Sound, .Alert, .Badge]

          UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: settings, categories: (notificationCategories as! Set<UIUserNotificationCategory>)))

        }
      }
    }
  }
}