Real time NSTask output to NSTextView with Swift

Since macOS 10.7, there’s also the readabilityHandler property on NSPipe which you can use to set a callback for when new data is available:

let task = NSTask()

task.launchPath = "/bin/sh"
task.arguments = ["-c", "echo 1 ; sleep 1 ; echo 2 ; sleep 1 ; echo 3 ; sleep 1 ; echo 4"]

let pipe = NSPipe()
task.standardOutput = pipe
let outHandle = pipe.fileHandleForReading

outHandle.readabilityHandler = { pipe in
    if let line = String(data: pipe.availableData, encoding: NSUTF8StringEncoding) {
        // Update your view with the new text here
        print("New ouput: \(line)")
    } else {
        print("Error decoding data: \(pipe.availableData)")
    }
}

task.launch()

I’m surprised nobody mentioned this, as it’s a lot simpler.

Leave a Comment