in swift my project i m planing to use terminal commands for getting some data. For this purpose i found some code and create a function. If i call this function one time there is no any problem. It works great. But if i call these function 2 times or 3 times consecutively, it works sometimes good , sometimes not.
func RunCommand(cmd : String, args : String...) -> (output: [String], error: [String], exitCode: Int32) {
let task = NSTask()
var output : [String] = []
var error : [String] = []
task.launchPath = cmd
task.arguments = args
let outpipe = NSPipe()
task.standardOutput = outpipe
let errpipe = NSPipe()
task.standardError = errpipe
task.launch()
let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String.fromCString(UnsafePointer(outdata.bytes)) {
string = string.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
output = string.componentsSeparatedByString("\n")
}
let errdata = errpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String.fromCString(UnsafePointer(errdata.bytes)) {
string = string.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
error = string.componentsSeparatedByString("\n")
}
let status = task.terminationStatus
task.waitUntilExit()
return (output, error, status)
}
This is my function. For example if i use below codes, sometimes mac and ip address printed well . But sometimes ip was empty, and mac ok. Sometimes both is empty.
let mac = RunCommand("/bin/sh",args:"-c", "ifconfig en1 | grep ether |awk '{print $2}'")
let ip = RunCommand("/bin/sh",args:"-c", "ifconfig | grep 'inet ' | grep -v 127.0.0.1 | cut -d\\ -f2")
print(mac)
print(ip)
Do u have any idea how i should use these codes to get take data always without any problem?