mac app打开后如何执行命令

Ste*_*han 4 macos swift

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

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")
})
Run Code Online (Sandbox Code Playgroud)

打开后我想执行命令“echo hello”,如completionHandler中所示。如何才能实现这一点呢?

Wil*_*eke 5

另一个解决方案:

do scriptApple 事件发送到终端:

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))")
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

要允许发送 Apple 事件:

  • 在“签名和功能”、“强化运行时”下,选中“Apple 事件”
  • 在 info.plist 中添加一行“隐私 - AppleEvents 发送使用说明”
  • 在权利中添加行“com.apple.security.temporary-exception.apple-events”和项目“com.apple.Terminal”