-3

I'm a complete swift noob. Using this code in xcode I get the result I need. I created a command line binary "menubar" that takes several arguments. I normally run it in the terminal "/bin/menubar getip", "/bin/menubar/getuser". I want to create a function based on the following working code.

import Cocoa
import Foundation

var task:NSTask = NSTask()
var pipe:NSPipe = NSPipe()

task.launchPath = "/bin/menubar"
task.arguments = ["getip"]
task.standardOutput = pipe
task.launch()

var handle = pipe.fileHandleForReading
var data = handle.readDataToEndOfFile()
var result_s = NSString(data: data, encoding: NSUTF8StringEncoding)
print(result_s)

I want to convert it to a function.

func commmand (argument: String) -> String
{

let task:NSTask = NSTask()
let pipe:NSPipe = NSPipe()

task.launchPath = "/bin/menubar"
task.arguments = ["argument"]
task.standardOutput = pipe
task.launch()

let handle = pipe.fileHandleForReading
let data = handle.readDataToEndOfFile()
let result_s = NSString(data: data, encoding: NSUTF8StringEncoding)
return result_s
}
commmand getip
nyitguy
  • 598
  • 4
  • 18

1 Answers1

1

Try this:

func commmand(argument: String) -> String
{

    let task:NSTask = NSTask()
    let pipe:NSPipe = NSPipe()

    task.launchPath = "/bin/menubar"
    task.arguments = [argument]
    task.standardOutput = pipe
    task.launch()

    let handle = pipe.fileHandleForReading
    let data = handle.readDataToEndOfFile()
    let result_s = String(data: data, encoding: NSUTF8StringEncoding)!
    return result_s
}

print(commmand("getip"))
Slayter
  • 1,172
  • 1
  • 13
  • 26
  • I get an exception on "return result_s" Cannot convert return expression of type "NSString?" to return type "String" – nyitguy Apr 21 '16 at 20:43
  • @Slayter, I tried your sample code but I'm getting this error ":0: note: 'NSPipe' was obsoleted in Swift 3". Do you know what can I use to replace NSPipe ? – user2924482 Apr 07 '17 at 16:23