Programmatically run at startup on Mac OS X?

Viewed 15053

How do I programmatically set an application bundle on Mac OS X to run when the user logs in?

Basically, the equivalent of the HKCU\Software\Microsoft\Windows\CurrentVersion\Run registry key in Windows.

5 Answers

You can also achieve this by invoking System Events via osascript. This should do the trick:

struct LaunchAtStartupHelper {
    static var isEnabled: Bool {
        get {
            shell(
                """
                osascript -e 'tell application "System Events" to get the name of every login item'
                """)
                .contains("MyAppName")
        }
        set {
            if newValue {
                shell(
                    """
                    osascript -e 'tell application "System Events" to make login item at end with properties {path:"/Applications/MyAppName.app", hidden:true}'
                    """)
            } else {
                shell(
                    """
                    osascript -e 'tell application "System Events" to delete login item "MyAppName"'
                    """)
            }
        }
    }
    // from https://stackoverflow.com/a/50035059/1072846
    @discardableResult
    private static func shell(_ command: String) -> String {
        let task = Process()
        let pipe = Pipe()

        task.standardOutput = pipe
        task.standardError = pipe
        task.arguments = ["-c", command]
        task.launchPath = "/bin/zsh"
        task.launch()

        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output = String(data: data, encoding: .utf8)!

        return output
    }
}

Related