简体   繁体   中英

Redirect NSLog to File in Swift not working

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.

The absoluteString property of an URL produces an URL string, eg

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM