如何在swiftUI中运行终端命令?
我正在尝试通过macOS应用程序测试终端命令的运行。我尝试运行的命令是“mkdir~/Desktop/test”,只需点击一个按钮,但我认为目前为止我使用的命令太简单,无法实际运行。或者可能是xCode的限制,不允许从模拟器访问我的桌面文件夹 下面是我的代码。 shell函数只是我在StackOverflow上找到的答案的复制粘贴:如何在swiftUI中运行终端命令?,swift,terminal,swiftui,swift5,Swift,Terminal,Swiftui,Swift5,我正在尝试通过macOS应用程序测试终端命令的运行。我尝试运行的命令是“mkdir~/Desktop/test”,只需点击一个按钮,但我认为目前为止我使用的命令太简单,无法实际运行。或者可能是xCode的限制,不允许从模拟器访问我的桌面文件夹 下面是我的代码。 shell函数只是我在StackOverflow上找到的答案的复制粘贴: struct ContentView: View { @discardableResult func shell(_ command: String) -&g
struct ContentView: View {
@discardableResult func shell(_ command: String) -> (String?, Int32) {
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
task.waitUntilExit()
return (output, task.terminationStatus)
}
var body: some View {
VStack{
Button(action: {
self.shell("mkdir ~/Desktop/test")
}) {
Text("Run Command").font(.body)
}
}.frame(width:500,height:500) }
}
我的最终目标是尝试运行屏幕截图命令“cd~/Desktop/| screenscapture test101.jpg”。如果可能的话,我也想知道我是否可以把这个命令放到shell函数中并运行它