Soufian Hossam Soufian Hossam - 4 months ago 41
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 com.apple.dock 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","com.apple.dock","persistent-apps","-array-add","'{\"tile-type\"=\"spacer-tile\";}';","killall Dock"]
let pipe = NSPipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
print(output)


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

Answer
  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.

Comments