Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thexande/f0695c57d255280e5ae2c3c7ef19c245 to your computer and use it in GitHub Desktop.
Save thexande/f0695c57d255280e5ae2c3c7ef19c245 to your computer and use it in GitHub Desktop.
private func executeShellCommand(_ command: String) {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.arguments = ["-c", command]
task.launchPath = "/bin/bash"
// task.launch()
let outputHandle = pipe.fileHandleForReading
outputHandle.waitForDataInBackgroundAndNotify()
// When new data is available
var dataAvailable : NSObjectProtocol!
dataAvailable = NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outputHandle, queue: nil) { notification -> Void in
let data = pipe.fileHandleForReading.availableData
if data.count > 0 {
if let str = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
print("Task sent some data: \(str)")
}
outputHandle.waitForDataInBackgroundAndNotify()
} else {
NotificationCenter.default.removeObserver(dataAvailable)
}
}
// When task has finished
var dataReady : NSObjectProtocol!
dataReady = NotificationCenter.default.addObserver(forName: Process.didTerminateNotification, object: pipe.fileHandleForReading, queue: nil) { notification -> Void in
print("Task terminated!")
NotificationCenter.default.removeObserver(dataReady)
}
// Launch the task
task.launch()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment