【发布时间】:2022-01-03 01:13:12
【问题描述】:
我是 SwiftUI 学习者。尝试在 MacOS 上运行一个简单的功能,该标准输出就像控制台一样在视图中显示。使用下面的代码,一旦执行完成,它就会在视图上打印输出。无论如何,我可以将输出重定向到实时查看吗?请帮我。提前致谢!
struct MainView : View {
@State var Log : String = ""
var body: some View {
VStack {
Form {
Section {
Text("\(Log)")
}
.onAppear {
DispatchQueue.global(qos: .background).async {
Task {
let output = await self.runCodeAsync()
DispatchQueue.main.async {
Log.append(output)
}
}
}
}
}
}
}
func runCodeAsync() async -> (String) {
let task = Process()
task.executableURL = URL(fileURLWithPath: "/sbin/ping")
task.arguments = [ "-c", "3", "127.0.0.1" ]
let outputPipe = Pipe()
task.standardOutput = outputPipe
await task.launch() //Xcode Warning: no 'async' operations occur within 'await' expression
let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
let output = String(decoding: outputData, as: UTF8.self)
return await output //Xcode Warning: no 'async' operations occur within 'await' expression
}
}
【问题讨论】: