我使用此代码从Cocoa应用程序运行命令:
extension String {
func runAsCommand() -> String {
let pipe = NSPipe()
let task = NSTask()
task.launchPath = "/bin/sh"
task.arguments = ["-c", String(format:"%@", self)]
task.standardOutput = pipe
let file = pipe.fileHandleForReading
task.launch()
if let result = NSString(data: file.readDataToEndOfFile(), encoding: NSUTF8StringEncoding) {
return result as String
}
else {return "--- Unable to initialize string from file data ---"}
}
}
示例:
"command".runAsCommand()
问题是,这会冻结我的应用程序。例如,如果该命令是打开其他应用程序(如Firefox),它会冻结我的主机应用程序,直到退出Firefox。我不想要那种行为。我该怎么办?