Swift NStask function

你说的曾经没有我的故事 提交于 2019-12-13 11:20:48

问题


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

回答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"))


来源:https://stackoverflow.com/questions/36779688/swift-nstask-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!