2

Directing the output of an NSTask object to a text view works for most of the commands I've tried, but not for a git clone. In that instance, the output goes to the Xcode console, even though I have no print statements in my code. The code as written below, goes to the console. If I use the commented out lines instead, the output goes to the text view.

    var cloneTask: NSTask!
    @IBOutlet var tv: NSTextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        cloneTask = NSTask()
        cloneTask.launchPath = "/usr/bin/git"
        cloneTask.arguments = ["clone", "https://github.com/edelmar/DHT22_Reader"]
        //cloneTask.launchPath = "/usr/bin/env"
        //cloneTask.arguments = ["pwd"]
        cloneTask.pipeOutputTo(tv)
        cloneTask.launch()
    }

pipeOutputTo: is a function in an extension on NSTask,

extension NSTask {
    func pipeOutputTo(logger: AnyObject) -> AnyObject {
        let pipe = NSPipe()
        self.standardOutput = pipe

        let stdoutHandle = pipe.fileHandleForReading
        stdoutHandle.waitForDataInBackgroundAndNotify()
        let observer = NSNotificationCenter.defaultCenter().addObserverForName(NSFileHandleDataAvailableNotification, object: stdoutHandle, queue: nil) { _ in
            let dataRead = stdoutHandle.availableData
            let stringRead = NSString(data: dataRead, encoding: NSUTF8StringEncoding)
            logger.append(stringRead as! String)
            if stringRead!.length > 0 {
                stdoutHandle.waitForDataInBackgroundAndNotify()
            }
        }
        return observer
    }
}

Does anyone know the reason for the difference in behavior?

rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • Could it be that git prints to standard error and you have to redirect that as well? – Martin R Jan 21 '16 at 06:12
  • @MartinR, I haven't tried that, but I will. I saw some posts on that, but since I'm not getting an error, I assumed it wouldn't print to there. – rdelmar Jan 21 '16 at 06:14
  • @MartinR, That was it, although, I only get the first line (Cloning into 'DHT22_Reader'...) instead of the whole output like I do in the console. – rdelmar Jan 21 '16 at 06:26

0 Answers0