如何使用 swift 在 Macosx 应用程序中执行 launchctl load start?

How can execute launchctl load start in a Macosx App using swift?

我想开发一个 MacOS 应用程序来管理我自己的一些进程。 本来以为应该用launchd,结果发现用launchd启动进程总是失败。错误如下:

0:86: execution error: 2020-03-11 17:15:02.213472+0800 launchctl[9835:373247] [All] launchctl start: launchctl start com.example.myprocess (3)

我已经关闭了沙箱。 我是用Apple Script申请root权限的。喜欢:

do shell script \"launchctl start com.example.myprocess\" with administrator privileges

我该如何处理,谢谢。

这是我的 swift 代码:

Button(action: {
//    let bundle = Bundle.main
//    let cmd = bundle.path(forResource: "test", ofType: "sh")!
//    let cmd = "launchctl load ~/Library/LaunchAgents/com.example.myprocess.plist"
    let cmd  = "launchctl start com.example.myprocess"
    let process = Process()
    process.launchPath = "/usr/bin/osascript"
    let arg = String.init(format: "do shell script \"%@\" with administrator privileges with prompt \"XXXXX\"", cmd)
    print(arg)
    process.arguments = ["-e", arg]
    process.launch()
    process.waitUntilExit()
    print("status: ", process.terminationStatus)
}) {
    Text("Start")
}.disabled(isRunning).padding(.trailing)

这是我的 plist 代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.example.myprocess</string>
        <key>ProgramArguments</key>
        <array>
            <string>/Users/tang/bin/myprocess</string>
            <string>start</string>
        </array>
        <key>StandardOutPath</key>
        <string>/Users/tang/myprocess.log</string>
        <key>StandardErrorPath</key>
        <string>/Users/tang/myprocess.log</string>
        <key>WorkingDirectory</key>
        <string>/Users/tang/</string>
    </dict>
</plist>

我使用QT开发的应用程序可以轻松调用shell脚本并执行launchd命令。 这是我的演示应用程序源代码:https://github.com/yiwenlong/launchduidemo