Soufian Hossam Soufian Hossam - 1 year ago 244
Swift Question

Using NSTask in swift to execute a terminal command

Hi i'm trying to make a simple program with swift to execute this command that adds a white space in Dock:

defaults write persistent-apps -array-add '{"tile-type"="spacer-tile";}'; killall Dock

this is the code i use:

let task = NSTask()
task.launchPath = "/usr/bin/defaults"
task.arguments = ["write","","persistent-apps","-array-add","'{\"tile-type\"=\"spacer-tile\";}';","killall Dock"]
let pipe = NSPipe()
task.standardOutput = pipe
task.standardError = pipe
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String

I get no errors but nothing happens. Can someone help me please?

Answer Source
  defaults write ... ; killall Dock

are two commands. When you type this line in the Terminal, it is passed to your shell (usually "bash" on OS X), and the shell then executes both commands sequentially.

On the other hand ,NSTask executes just a single command and does nothing of the magic that a shell usually does. In your case all the arguments, including the final "killall Dock", are passed as arguments to /usr/bin/defaults.

A possible solution would be to execute two NSTasks sequentially, one for the defaults command, and one for the killall command.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download