将 NSLog 重定向到 Swift 中的文件不起作用 [英] Redirect NSLog to File in Swift not working

查看:18
本文介绍了将 NSLog 重定向到 Swift 中的文件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 NSLog 发送到在模拟器、IOS 10.2 上运行的 Swift 3 中的文件,但没有生成任何内容

如何将 NSLog 登录到文件中

func redirectConsoleLogToDocumentFolder() {让文件=文件.txt"if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {让 logPath = dir.appendingPathComponent(file).absoluteString打印(日志:(日志路径)")freopen(logPath, "a+", stderr)}NSLog("打印 nslog")}

输出

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

唯一的效果是输出不再打印到控制台.

我试过了

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

以及其他各种组合

我可以用我收到的路径写入文件,所以没有任何问题

我希望在路径中看到一个名为 file.txt 的文件,并且该文件包含print nslog".我曾尝试先创建文件但没有成功.

解决方案

URLabsoluteString 属性产生一个 URL 字符串,例如

<前>file:///path/to/file.txt

不适合作为 freopen() 的参数.要将文件路径作为字符串获取,请改用 path:

let logPath = dir.appendingPathComponent(file).path

最好使用专用方法将 URL 路径传递给系统调用:

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

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

这篇关于将 NSLog 重定向到 Swift 中的文件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆