Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute external program from Swift?

I am new in Swift and I did not found anything about executing external programs or access external processes using Swing language.

Is it possible to do in the current stage of the language development or I should use Objective-C instead?

Maybe there are some Objective-C libraries that can be used inside my Swift program?

Thanks.

like image 211
Dmytro Plekhotkin Avatar asked Sep 08 '14 14:09

Dmytro Plekhotkin


2 Answers

You can run external programs using NSTask. For example, from Circle and Square:

import Foundation

func executeCommand(command: String, args: [String]) -> String {

    let task = NSTask()

    task.launchPath = command
    task.arguments = args

    let pipe = NSPipe()
    task.standardOutput = pipe
    task.launch()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = NSString(data: data, encoding: NSUTF8StringEncoding)

    return output        
}

let commandOutput = executeCommand("/bin/echo", ["Hello, I am here!"])
println("Command output: \(commandOutput)")
like image 198
Rob Napier Avatar answered Nov 16 '22 23:11

Rob Napier


Improved version of Rob's answer (in that you don't need to specify the full path of your executable), and also updated for Swift 3:

import Foundation

func execCommand(command: String, args: [String]) -> String {
    if !command.hasPrefix("/") {
        let commandFull = execCommand(command: "/usr/bin/which", args: [command]).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        return execCommand(command: commandFull, args: args)
    } else {
        let proc = Process()
        proc.launchPath = command
        proc.arguments = args
        let pipe = Pipe()
        proc.standardOutput = pipe
        proc.launch()
        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        return String(data: data, encoding: String.Encoding.utf8)!
    }
}
like image 21
qed Avatar answered Nov 16 '22 23:11

qed