使用不使用Swift的freopen将日志内容写入文本文件

时间:2017-07-18 10:57:31

标签: ios iphone swift freopen

我想将每个print()内容写入Swift 3.0中的文本文件中。 它在Objective-C中运行良好,但在Swift 3.0中无效。 我使用的代码如下,

    func redirectLogToDocuments() {

    let docDirectory: NSString = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
    let logpath = docDirectory.appendingPathComponent("Logfile.txt")

    freopen(logpath.cString(using: String.Encoding.utf8)!, "a+", stdin)
    freopen(logpath.cString(using: String.Encoding.utf8)!, "a+", stdout)
    freopen(logpath.cString(using: String.Encoding.utf8)!, "a+", stderr)                
}

请帮帮我。

1 个答案:

答案 0 :(得分:1)

 func redirectLogToDocuments() {
    let allPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = allPaths.first!
    let pathStringComponent = "/" + LoggingConstants.LogFileName + "." + LoggingConstants.LogFileType
    let pathForLog = (documentsDirectory as NSString).appending(pathStringComponent)
    freopen(pathForLog.cString(using: String.Encoding.ascii)!, "a+", stderr)
}

在didFinishLaunching()中使用上述方法,然后使用NSLog()语句而不是print(),您将获得所需的内容。