Search code examples
swiftmacosapplescriptlaunchd

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


I want to develop an MacOS app to manage some of my own processes. I thought I should use launchd, but I found that when I use launchd to start the process, it always fails. The error is as follows:

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

I have closed the sandbox. I used Apple Script to apply for root permissions. Like:

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

How should i deal with this, thanks.

Here is my swift code:

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)

Here is my plist code:

<?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>

Solution

  • The app I developed using QT can easily call shell scripts and execute launchd commands. This is my demo app source code: https://github.com/yiwenlong/launchduidemo