【问题标题】:How to output NSTextView Content to Textfile如何将 NSTextView 内容输出到文本文件
【发布时间】:2018-12-21 07:36:36
【问题描述】:

我有以下代码并想导出结果 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()
}

【问题讨论】:

    标签: xcode macos swift4.2


    【解决方案1】:

    试试下面这段代码(修改和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 */}
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      相关资源
      最近更新 更多