gpt4 book ai didi

swift - mac app打开后如何执行命令

转载 作者:行者123 更新时间:2023-12-04 00:13:36 37 4
gpt4 key购买 nike

我想在我的应用打开系统终端应用后执行命令。我使用以下内容打开终端应用程序:

let url = NSURL(fileURLWithPath: "/System/Applications/Utilities/Terminal.app", isDirectory: true) as URL
let configuration = NSWorkspace.OpenConfiguration()
NSWorkspace.shared.openApplication(at: url, configuration: configuration, completionHandler: { app, error in
//app.executeMyCommand("echo hello")
})

打开后我要执行命令“echo hello”,如completionHandler所示。如何做到这一点?

最佳答案

另一种解决方案:

向终端发送一个 do script Apple 事件:

let terminalScript = "echo hello"
if let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.Terminal") {
let configuration = NSWorkspace.OpenConfiguration()
let doScriptEvent = NSAppleEventDescriptor(eventClass: kAECoreSuite,
eventID: kAEDoScript, targetDescriptor: nil, returnID: AEReturnID(kAutoGenerateReturnID),
transactionID: AETransactionID(kAnyTransactionID))
doScriptEvent.setParam(NSAppleEventDescriptor(string: terminalScript), forKeyword:keyDirectObject)
configuration.appleEvent = doScriptEvent
NSWorkspace.shared.openApplication(at: url, configuration: configuration, completionHandler: { app, error in
if error != nil {
print("Error: \(String(describing: error))")
}
})
}

允许发送 Apple 事件:

  • 在“签名和功能”、“强化运行时”下,选中“Apple 事件”
  • 在 info.plist 中添加一行 'Privacy - AppleEvents Sending Usage Description'
  • 在权利中添加一行“com.apple.security.temporary-exception.apple-events”和项目“com.apple.Terminal”

关于swift - mac app打开后如何执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65925082/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com