本文介绍了Swift NStask函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我是一个完整的swift noob。在xcode中使用这个代码我得到我需要的结果。我创建了一个命令行二进制menubar,需要几个参数。我通常在终端/ 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


解决方案

尝试:

  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))


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
解决方案

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

这篇关于Swift NStask函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 09:49