-3

我是一个完全快速的菜鸟。在 xcode 中使用这段代码,我得到了我需要的结果。我创建了一个带有多个参数的命令行二进制“菜单栏”。我通常在终端“/bin/menubar getip”、“/bin/menubar/getuser”中运行它。我想根据以下工作代码创建一个函数。

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)

我想将其转换为函数。

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
4

1 回答 1

1

尝试这个:

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"))
于 2016-04-21T20:40:48.173 回答