如何启动外部流程?

时间:2018-01-19 03:16:14

标签: swift macos process

我正在阅读swift的文档并遇到了类型方法。例如:https://developer.apple.com/documentation/foundation/process

提供的类型方法是:

const doSomething = () => { // do something } const myObject = { doSomething: () => { // do something } } fetch('/path/to/page').then(() => { // do something }) (() => { // do something immediately })()

如何在我的代码中使用它?例如,当我按下按钮?如何向terminationHandler添加清理功能?

1 个答案:

答案 0 :(得分:8)

macos应用中,您可以使用run启动外部流程,例如:

1)一次性执行:

let url = URL(fileURLWithPath:"/bin/ls")
do {
   try Process.run(url, arguments: []) { (process) in
      print("\ndidFinish: \(!process.isRunning)")
   }
} catch {}

2)您可能希望使用Process实例来更轻松地设置其行为,这样做:

let process = Process()
process.executableURL = URL(fileURLWithPath:"/bin/ls")
process.arguments = ["-la"]
process.terminationHandler = { (process) in
   print("\ndidFinish: \(!process.isRunning)")
}
do {
  try process.run()
} catch {}

所以我确实启动了ls命令(你可以检查你的控制台的结果),然后在关闭terminationHandler我得到了这样的过程。