I'm trying to simply utilize the system ping function through bash and output to a window.
The problem I'm running into and what I'd like to see if there is a work-around for (perhaps I'm just doing this wrong, I'm a novice) is that currently if I run this app when I click the "ping" button the application seems to freeze up (mac pinwheel) while it waits for the ping command to complete the 10 pings but then shows the full text of the bash output in the window. So the final product looks correct, but I'd like to not look like it's crashing.
Here's a GIF of it playing out. You can't see the mouse pinwheeling but the moment I click the Ping button it's spinning till the data appears.
What I'd like for it to do would be to just "stream" the output to the window instead of seeming to lock up and wait for the pings to complete. I'd like to see each of the pings appearing in the window in real time.
Here is the function I'm using to execute the bash command with arguments:
import Foundation
func runCmd(cmd : String, args : String...) -> String {
let task = Process()
task.launchPath = cmd
task.arguments = args
let outpipe = Pipe()
task.standardOutput = outpipe
task.launch()
let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
guard let string = String(data: outdata, encoding: .utf8) else { return ""}
let output = string.trimmingCharacters(in: .newlines)
return (output)
}
Here is my ViewController:
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var resultsOutput: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func pingbutton(_ sender: Any) {
let eIP = runCmd(cmd: "/bin/bash", args: "-c", "ipconfig getifaddr en0")
let pingip = runCmd(cmd: "/bin/bash", args: "-c", "ping -c 10 -S \(eIP) www.google.com")
resultsOutput.stringValue = pingip
}
}
The app currently works and produces the results I'm looking for, but I'd like to if possible have it produce each line of the output as it is generated instead of seeming to freeze up till the 10 ping count is complete and dumping the full results in at once.
Any assistance is greatly appreciated!