Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

ios - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...