Created
June 14, 2020 05:53
-
-
Save thexande/f0695c57d255280e5ae2c3c7ef19c245 to your computer and use it in GitHub Desktop.
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
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