我有一个外部控制台应用程序(在OS X上),该应用程序发出从1到100到标准输出的整数序列,大约每秒一次。
我是Swift,我需要使用该数字流来更新进度指示器。
这是我到目前为止的代码:
class MasterViewController: NSViewController {
@IBOutlet weak var progressIndicator: NSProgressIndicator!
override func viewDidLoad() {
super.viewDidLoad()
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "sleep 1; echo 10 ; sleep 1 ; echo 20 ; sleep 1 ; echo 30 ; sleep 1 ; echo 40; sleep 1; echo 50; sleep 1; echo 60; sleep 1"]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let string = String(data: data, encoding: String.Encoding.utf8) {
print(string)
}
}
该代码有效(即,它从命令行实用程序读取输出并相应地修改进度指示器),但是在该实用程序退出后,它进行了所有更改(同时使我的UI等待)。
我将如何设置它,以便它读取后台应用程序的输出并实时更新进度指示器?
供以后参考,下面是我如何使其最终工作(现在已针对Swift 3更新):
class ViewController: NSViewController {
@IBOutlet weak var progressIndicator: NSProgressIndicator!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "sleep 1; echo 10 ; sleep 1 ; echo 20 ; sleep 1 ; echo 30 ; sleep 1 ; echo 40; sleep 1; echo 50; sleep 1; echo 60; sleep 1"]
let pipe = Pipe()
task.standardOutput = pipe
let outHandle = pipe.fileHandleForReading
outHandle.waitForDataInBackgroundAndNotify()
var progressObserver : NSObjectProtocol!
progressObserver = NotificationCenter.default.addObserver(
forName: NSNotification.Name.NSFileHandleDataAvailable,
object: outHandle, queue: nil)
{
notification -> Void in
let data = outHandle.availableData
if data.count > 0 {
if let str = String(data: data, encoding: String.Encoding.utf8) {
if let newValue = Double(str.trimEverything) {
self.progressIndicator.doubleValue = newValue
}
}
outHandle.waitForDataInBackgroundAndNotify()
} else {
// That means we've reached the end of the input.
NotificationCenter.default.removeObserver(progressObserver)
}
}
var terminationObserver : NSObjectProtocol!
terminationObserver = NotificationCenter.default.addObserver(
forName: Process.didTerminateNotification,
object: task, queue: nil)
{
notification -> Void in
// Process was terminated. Hence, progress should be 100%
self.progressIndicator.doubleValue = 100
NotificationCenter.default.removeObserver(terminationObserver)
}
task.launch()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
// This is just a convenience extension so that I can trim
// off the extra newlines and white spaces before converting
// the input to a Double.
fileprivate extension String {
var trimEverything: String {
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
现在,一旦子进程完成,进度条将前进到60%,然后跳到100%。
您正在主线程上同步读取,因此直到函数返回主循环后,UI才会更新。
有(至少)两种可能的方法来解决此问题:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句