Redirect NSLog to File in Swift not working

自古美人都是妖i 提交于 2019-12-17 10:05:53

问题


I am trying to send NSLog to a file in Swift 3 running on Simulator, IOS 10.2 and nothing is being produced

How to NSLog into a file

func redirectConsoleLogToDocumentFolder() {
    let file = "file.txt"
    if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

        let logPath = dir.appendingPathComponent(file).absoluteString
        print("log:\(logPath)")
        freopen(logPath, "a+", stderr)
    }
    NSLog("print nslog")
}

Output

~/Library/Developer/CoreSimulator/Devices/A7B717-3ED8-493A-9778-C594AF9FF446/data/Containers/Data/Application/B0386-64BB-46EB-9BF2-65209FC748CD/Documents/file.txt

The only effect is that the output is no longer printed to the console.

I have tried

freopen(logPath.cString(using: .utf8), "a+", stderr)

and various other combinations

I have no trouble writing to a file with the path I am receiving so there is nothing wrong with that

I expected to see a file created called file.txt in the path and the file to contains "print nslog". I have tried creating the file first without success.


回答1:


The absoluteString property of an URL produces an URL string, e.g.

    file:///path/to/file.txt

which is not suitable as argument to freopen(). To get the file path as a string, use path instead:

let logPath = dir.appendingPathComponent(file).path

Better, use the dedicated method to pass an URLs path to a system call:

let logFileURL = dir.appendingPathComponent(file)
logFileURL.withUnsafeFileSystemRepresentation {
    _ = freopen($0, "a+", stderr)
}


来源:https://stackoverflow.com/questions/41680004/redirect-nslog-to-file-in-swift-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!