一次注册多个Siri快捷方式

时间:2018-11-01 06:18:40

标签: ios swift ios12 siri sirishortcuts

我编写了一些代码,尝试通过迭代枚举值一次注册多个Siri快捷方式

当我运行代码并打开设置应用程序时,它仅显示上次注册的快捷方式。

我应该如何一次注册多个Siri快捷方式?

static func registerSiriShortcut(to responder: UIResponder) {

    if #available(iOS 12.0, *) {
      let cases = SiriShortcutType.allCases
      for type in cases {

        let activity = NSUserActivity(activityType: type.siriActivityType)
        activity.title = type.siriShortcutTitle
        activity.isEligibleForSearch = true
        activity.isEligibleForPrediction = true

        responder.userActivity = activity
        responder.userActivity?.becomeCurrent()
      }
    }

  }

1 个答案:

答案 0 :(得分:3)

您的代码对我来说似乎还可以。通常,“设置”->“ Siri”仅显示最近注册的快捷方式。如果转到“设置”->“ Siri”->“所有快捷方式”,则将在其中看到所有名称。

正如您在代码activity.isEligibleForSearch = true中提到的那样,也可以从家中向右轻扫以进行电话搜索,然后键入快捷方式,您也应该会看到快捷方式项的弹出窗口。

编辑1:我的代码证明:

  1. Info.plist:您需要提及多少个NSUserActivityTypes:

    <Key>NSUserActivityTypes</key>
    <array> 
    <string>com.rio.SiriShortcuts.makeGreen</string>
    <string>com.rio.SiriShortcuts.makeRed</string>
    </array>
    
  2. 枚举类:

    enum SiriShortcutType {
    case makeRed
    case makeGreen
    
    var siriActivityType: String {
        switch self {
            case .makeRed:
            return "com.rio.SiriShortcuts.makeRed"
            case .makeGreen:
            return "com.rio.SiriShortcuts.makeGreen"
        }
    }
    
    var siriShortcutTitle: String {
        switch self {
        case .makeRed:
            return "Make View Red"
        case .makeGreen:
            return "Make View Green"
        }
    }
    
    var color: String {
        switch self {
        case .makeRed:
            return "red"
        case .makeGreen:
            return "green"
        }
    }
    
    static let allCases:[SiriShortcutType] = [.makeRed, .makeGreen]
    }
    
  3. 现在在VC中使用我的注册方法(通过按钮操作调用):

     func registerSiriShortcut() {
    if #available(iOS 12.0, *) {
        let cases = SiriShortcutType.allCases
        var suggestions: [INShortcut] = []
        for type in cases {
    
            let activity = NSUserActivity(activityType: type.siriActivityType)
            activity.userInfo = ["color" : type.color]
            activity.title = type.siriShortcutTitle
            activity.isEligibleForSearch = true
            activity.isEligibleForPrediction = true
            activity.persistentIdentifier = NSUserActivityPersistentIdentifier(type.siriActivityType)
            suggestions.append(INShortcut(userActivity: activity))
        }
        INVoiceShortcutCenter.shared.setShortcutSuggestions(suggestions)
    }
    }
    

编辑1 :INShortcut支持多个Siri快捷方式:请参阅更新的registerSiriShortcut()。