4

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?

Soufian Hossam
  • 487
  • 5
  • 16
  • Please, do some research. On StackOverflow you can find posts dealing with `NSTask`, such as: [this](http://stackoverflow.com/questions/35854503/swift-2-1-osx-shell-commands-using-nstask-work-when-run-from-xcode-but-not-when) or [this](http://stackoverflow.com/questions/36779688/swift-nstask-function). Also, consult `NSTask` class reference pages. – user3078414 Jul 16 '16 at 16:51
  • who told you that i didn't ?, I came here because i didn't find any solution. – Soufian Hossam Jul 16 '16 at 17:05

2 Answers2

4

This is the code that worked for me:

    let task = NSTask()
    task.launchPath = "/usr/bin/defaults"
    task.arguments = ["write","com.apple.dock","persistent-apps","-array-add","{\"tile-type\"=\"spacer-tile\";}"]
    let pipe = NSPipe()
    task.standardOutput = pipe
    task.standardError = pipe
    task.launch()
    task.waitUntilExit()

    let task2 = NSTask()
    task2.launchPath = "/usr/bin/killall"
    task2.arguments = ["Dock"]
    let pipe2 = NSPipe()
    task2.standardOutput = pipe2
    task2.standardError = pipe2
    task2.launch()
    task2.waitUntilExit()


    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
    print(output)
Soufian Hossam
  • 487
  • 5
  • 16
2
  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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382