【问题标题】:SwiftUI async redirect output on view like console output (Realtime)SwiftUI异步重定向输出,如控制台输出(实时)
【发布时间】: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
    }
}

【问题讨论】:

    标签: swift xcode macos swiftui


    【解决方案1】:

    试试下面的代码,不要使用异步:

    EDIT-1:

    struct MainView: View {
        @State var log: String = "testing"
        
        var body: some View {
            Text(log)
                .onAppear {
                   runCode()
                }
                .frame(width: 444, height: 444)
        }
        
        func runCode() {
            let task = Process()
            task.executableURL = URL(fileURLWithPath: "/sbin/ping")
            task.arguments = [ "-c", "3", "127.0.0.1" ]
            let outputPipe = Pipe()
            task.standardOutput = outputPipe
            let outputHandle = outputPipe.fileHandleForReading
            outputHandle.readabilityHandler = { pipe in
                if let ouput = String(data: pipe.availableData, encoding: .utf8) {
                    if !ouput.isEmpty {
                        log += " " + ouput
                        print("----> ouput: \(ouput)")
                    }
                } else {
                    print("Error decoding data: \(pipe.availableData)")
                }
            }
            task.launch()
        }
    }
    

    【讨论】:

    • 不,这也不起作用。它仅在执行完成后更新一次视图。
    • 好的,用新代码更新了我的答案。
    • 太棒了。非常感谢@workingdog
    猜你喜欢
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    相关资源
    最近更新 更多