我有以下代码,想导出的结果
self.logger.string += line
到文件。怎么办?
func syncShellExec(path: String, args: [String] = []) {
//let script = [path!]
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = [path] + args
let outputPipe = Pipe()
let filelHandler = outputPipe.fileHandleForReading
process.standardOutput = outputPipe
filelHandler.readabilityHandler = { pipe in
let data = pipe.availableData
if let line = String(data: data, encoding: .utf8) {
// Update your view with the new text here
// Bounce back to the main thread to update the UI
DispatchQueue.main.async {
self.logger.string += line
}
} else {
print("Error decoding data: \(data.base64EncodedString())")
}
}
process.launch()
process.waitUntilExit()
filelHandler.readabilityHandler = nil
//self.loggerScroll.flashScrollers()
}
答案 0 :(得分:0)
在下面尝试以下代码(已修改和stolen from this related answer):
let file = "file.txt" //this is the file. we will write to and read from it
let text = self.logger.string //the text we'll write
// we'll write the file in the user's documents directory
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */}
}