0

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?

  • Your first command can be shortened to `ifconfig en1 | awk '/ether/'{print $2}'` - there is no need to use `grep` and `awk`. – Mark Setchell Jan 28 '16 at 10:11
  • Your second command can probably return more than one line and it may depend if your wifi is running - so you need to make it more specific in what you are trying to achieve. Try running it in the Terminal a few times and see what you get. – Mark Setchell Jan 28 '16 at 10:12
  • 1
    That code [looks familiar](http://stackoverflow.com/a/29519615/1187415) :) – Martin R Jan 28 '16 at 10:31

1 Answers1

0

I had the same problem, which is funny because it looks like we copied and pasted the same code example. I resolved my problem by simplifying the code, ultimately removing the "if var string..." statements.

Community
  • 1
  • 1
AllenMoh
  • 476
  • 2
  • 13