以编程方式重新启动 OSX 应用程序

Restarting OSX app programmatically

我需要重新启动我的应用程序,以防我重新加载需要从头开始的内容。我试过这个

  let path = NSBundle.mainBundle().resourcePath!.stringByDeletingLastPathComponent.stringByDeletingLastPathComponent
  let task = NSTask()
  task.launchPath = "open"
  task.arguments = [path]
  task.launch()
  exit(0)

但我在 open

时收到错误消息

launch path not accessible

虽然问题本身微不足道(忘记了路径),但我留下了问题和答案,以防其他人需要相同的功能。

let path = NSBundle.mainBundle().resourcePath!.stringByDeletingLastPathComponent.stringByDeletingLastPathComponent
let task = NSTask()
task.launchPath = "/usr/bin/open"
task.arguments = [path]
task.launch()
exit(0)

编辑(Sw3 的每日 Swift 语法更改;也适用于 Sw4):

let url = URL(fileURLWithPath: Bundle.main.resourcePath!)
let path = url.deletingLastPathComponent().deletingLastPathComponent().absoluteString
let task = Process()
task.launchPath = "/usr/bin/open"
task.arguments = [path]
task.launch()
exit(0)