Redirect NSLog to File in Swift not working

2019-01-09 19:17发布

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.

标签: ios swift swift3
1条回答
闹够了就滚
2楼-- · 2019-01-09 20:09

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)
}
查看更多
登录 后发表回答