cocoa 调起终端执行命令

251 阅读1分钟
/*

 1. note the two keys in info.plist

 <key>NSAppleEventsUsageDescription</key>

 <string>Run Scripts</string>

 <key>NSFileProviderDomainUsageDescription</key>

 <string></string>

 

 2. use as follows

 TerminalScript.executeInTerminal("cd /Users/dfpo/myProj/hibuildIpa;pod install")

 */

class TerminalScript {

    static func executeInTerminal(_ command: String?) {

        guard let command = command, !command.isEmpty else {

            return

        }

        let scriptText =

        """

        tell application "Terminal"

        if not (exists window 1) then reopen

        activate

        do script "\(command)" in front window

        end tell

        """

        let script = NSAppleScript(source: scriptText)

        var error: NSDictionary?

        script?.executeAndReturnError(&error)

        guard var errorMessage = error?["NSAppleScriptErrorBriefMessage"] as? String  else {

            return

        }

        if let errorNumber = error?["NSAppleScriptErrorNumber"] as? NSNumber,

           errorNumber == NSNumber(integerLiteral: -1728) {

            errorMessage = "Please open Terminal app"

        }

        let alert = NSAlert()

        alert.messageText = "Something went wrong"

        alert.informativeText = errorMessage

        alert.alertStyle = NSAlert.Style.warning

        alert.addButton(withTitle: "OK")

        alert.runModal()

        

    }

}