You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Swift(macOS)应用中通过Picker展示Siri快捷指令

macOS Swift应用与Siri快捷指令交互指南

一、快捷指令的存储位置

macOS上的Siri快捷指令默认存储在用户目录的~/Library/Shortcuts/文件夹中,每个快捷指令对应一个.shortcut后缀的文件。但不建议直接读取该目录:

  • 沙箱化的应用可能没有访问该目录的权限
  • 苹果可能在后续系统版本中修改存储路径或格式

因此,获取快捷指令的推荐方式是使用官方提供的Shortcuts框架。

二、在Picker中展示快捷指令的实现步骤

1. 配置项目权限

在Info.plist中添加NSShortcutsUsageDescription键,填写访问快捷指令的理由(例如:"需要访问您的快捷指令以在应用内调用执行"),否则应用会被拒绝访问权限。

2. 使用Shortcuts框架获取快捷指令列表

导入Shortcuts框架后,通过SHWorkflowQuery异步获取所有用户快捷指令:

import Shortcuts

func fetchUserShortcuts() async throws -> [SHWorkflow] {
    let query = SHWorkflowQuery()
    return try await query.workflows()
}

3. 在SwiftUI Picker中展示快捷指令

将获取到的SHWorkflow数组作为Picker的数据源,提取快捷指令名称作为显示文本,用唯一标识符作为选择标记:

struct ShortcutsSelectionView: View {
    @State private var userShortcuts: [SHWorkflow] = []
    @State private var selectedShortcutID: String?
    
    var body: some View {
        Picker("选择快捷指令", selection: $selectedShortcutID) {
            ForEach(userShortcuts, id: \.identifier) { shortcut in
                Text(shortcut.name)
                    .tag(shortcut.identifier)
            }
        }
        .task {
            do {
                userShortcuts = try await fetchUserShortcuts()
                selectedShortcutID = userShortcuts.first?.identifier
            } catch {
                print("获取快捷指令失败:\(error.localizedDescription)")
            }
        }
    }
}

4. 调用选中的快捷指令(可选)

如果需要执行选中的快捷指令,可以使用SHWorkflow的run()方法:

func runSelectedShortcut() async throws {
    guard let selectedID = selectedShortcutID,
          let shortcut = userShortcuts.first(where: { $0.identifier == selectedID }) else {
        return
    }
    try await shortcut.run()
}

内容的提问来源于stack exchange,提问作者iStuces

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 13:32:45