我正在为 macOS 开发一个 Swift 应用程序。 我希望它能够与用户的快捷方式交互(阻止Shortcuts应用程序中的程序,图1)。但我找不到他们...
您知道它们位于哪里以及如何在选择器中显示它们(图 2)以便用户可以在应用程序中选择它们吗?
提前致谢!
如图。 1
如图。 2
您可以使用
shortcuts list
命令获取快捷方式的名称。您可以使用 Process
在 Swift 中运行它。这是一个简单的例子:
struct ContentView: View {
@State var shortcuts = [ShortcutInfo]()
@State var selection = ""
var body: some View {
Picker("Pick a shortcut", selection: $selection) {
ForEach(shortcuts) {
Text($0.name)
}
}
.task {
let shortcuts = (try? await loadShortcutNames()) ?? []
self.shortcuts = shortcuts
selection = shortcuts.first?.id ?? ""
}
// use "shortcuts run" to run the shortcut
// there additional options to specify input
// see "shortcuts help run" for more info
Button("Run") {
let process = Process()
process.executableURL = URL(filePath: "/usr/bin/shortcuts")
process.arguments = ["run", selection]
try? process.run()
}
}
}
struct ShortcutInfo: Identifiable {
let id: String
let name: String
}
func loadShortcutNames() async throws -> [ShortcutInfo] {
let process = Process()
process.executableURL = URL(filePath: "/usr/bin/shortcuts")
// also get the UUID of the shortcut so that ShortcutInfo can be Identifiable
process.arguments = ["list", "--show-identifiers"]
let pipe = Pipe()
process.standardOutput = pipe
return try await withTaskCancellationHandler {
try process.run()
return try await pipe.fileHandleForReading.bytes.lines.compactMap { line in
// parse the shortcut name and ID
guard let (_, name, id) = line.wholeMatch(of: /(.*) \(([A-Z0-9-]*)\)/)?.output else {
return nil
}
return ShortcutInfo(id: String(id), name: String(name))
}.reduce(into: []) { $0.append($1) }
} onCancel: {
process.terminate()
}
}