Real time NSTask output to NSTextView with Swift -


i'm using nstask run rsync, , i'd status show in text view of scroll view inside window. right have this:

let pipe = nspipe() task2.standardoutput = pipe task2.launch()  let data = pipe.filehandleforreading.readdatatoendoffile() let output: string = nsstring(data: data, encoding: nsasciistringencoding)! string  textview.string = output 

and get's me of statistics transfer, i'd output in real time, get's printed out when run app in xcode, , put text view. there way this?

you can read asynchronously pipe, using notifications. here simple example demonstrating how works, helps started:

let task = nstask() task.launchpath = "/bin/sh" task.arguments = ["-c", "echo 1 ; sleep 1 ; echo 2 ; sleep 1 ; echo 3 ; sleep 1 ; echo 4"]  let pipe = nspipe() task.standardoutput = pipe let outhandle = pipe.filehandleforreading outhandle.waitfordatainbackgroundandnotify()  var obs1 : nsobjectprotocol! obs1 = nsnotificationcenter.defaultcenter().addobserverforname(nsfilehandledataavailablenotification,     object: outhandle, queue: nil) {  notification -> void in         let data = outhandle.availabledata         if data.length > 0 {             if let str = nsstring(data: data, encoding: nsutf8stringencoding) {                 print("got output: \(str)")             }             outhandle.waitfordatainbackgroundandnotify()         } else {             print("eof on stdout process")             nsnotificationcenter.defaultcenter().removeobserver(obs1)         } }  var obs2 : nsobjectprotocol! obs2 = nsnotificationcenter.defaultcenter().addobserverforname(nstaskdidterminatenotification,     object: task, queue: nil) { notification -> void in         print("terminated")         nsnotificationcenter.defaultcenter().removeobserver(obs2) }  task.launch() 

instead of print("got output: \(str)") can append received string text view.

the above code assumes runloop active (which case in default cocoa application).


Popular posts from this blog