I have two classes in Swift, one is a ViewController.swift, another has some business logic, called Brain.swift. In Brain.swift I have a class which contains a function called convert() which executes an NSTask.
In ViewController.swift all of the UI updating occurs.
What I would like to accomplish is getting the output of the convert()'s NSTask into a TextView in the ViewController.
I have implemented the solution from this answer, but I'm a bit of a novice so I'm unsure how to return it as a class property in real time to be accessible by other classes.
Brain.swift
import Foundation
internal func convert(chosenFile: NSURL, addText: (newText: String) -> Void) {
let bundle = NSBundle.mainBundle()
let task = NSTask()
let outputPipe = NSPipe()
task.standardOutput = outputPipe
let outHandle = outputPipe.fileHandleForReading
outHandle.readabilityHandler = { outputPipe in
if let line = String(data: outputPipe.availableData, encoding: NSUTF8StringEncoding) {
addText(newText: line)
} else {
print("Error decoding data: \(outputPipe.availableData)")
}
}
task.launch()
task.waitUntilExit()
}
ViewController.swift
@IBAction func Run(sender: AnyObject) {
let qualityOfServiceClass = QOS_CLASS_USER_INITIATED
let userInitiatedQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(userInitiatedQueue, {
self.btnConvert.enabled = false
self.btnSelect.enabled = false
self.activitySpinner.hidden = false
self.activitySpinner.startAnimation(self)
convert(self.inputFile.chosenFile) { newText in
self.statusText.stringValue = "\(newText)"
}
})
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.statusText.stringValue = "Done!"
self.activitySpinner.hidden = true
self.activitySpinner.stopAnimation(self)
self.btnSelect.enabled = true
})
}