Created
January 12, 2016 23:00
-
-
Save kristopherjohnson/1246d909462fb31dc800 to your computer and use it in GitHub Desktop.
Demonstrate launching an `NSTask` and asynchronously reading its output.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
/// Demonstrate launching an `NSTask` and asynchronously reading its output. | |
/// | |
/// Credit: <http://stackoverflow.com/a/23938137/1175> | |
func testTaskOutputPipe() { | |
let task = NSTask() | |
task.launchPath = "/bin/ls" | |
task.arguments = ["-l", "/Applications"] | |
let stdoutPipe = NSPipe() | |
task.standardOutput = stdoutPipe | |
let stdoutHandle = stdoutPipe.fileHandleForReading | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { | |
var data = stdoutHandle.availableData | |
while data.length > 0 { | |
if let s = NSString(data: data, encoding: NSUTF8StringEncoding) { | |
print(s, terminator: "") | |
data = stdoutHandle.availableData | |
} | |
} | |
} | |
task.launch() | |
task.waitUntilExit() | |
} | |
testTaskOutputPipe() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment