在Swift中将NSLog重定向到File无法正常工作 [英] Redirect NSLog to File in Swift not working
问题描述
我正在尝试将NSLog发送到在Simulator,IOS 10.2上运行的Swift 3中的文件,并且没有生成任何内容
I am trying to send NSLog to a file in Swift 3 running on Simulator, IOS 10.2 and nothing is being produced
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")
}
输出
~/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.
我试过
freopen(logPath.cString(using: .utf8), "a+", stderr)
以及其他各种组合
使用我的路径写一个文件我没有问题接收所以没有任何问题
I have no trouble writing to a file with the path I am receiving so there is nothing wrong with that
我希望在路径中看到一个名为file.txt的文件,并且文件包含print nslog。我尝试先创建文件但没有成功。
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.
推荐答案
absoluteString
URL的属性
生成一个URL字符串,例如
The absoluteString
property of an URL
produces an URL string, e.g.
file:///path/to/file.txt
这不适合作为 freopen()的参数
。
要将文件路径作为字符串,请改为使用路径
:
let logPath = dir.appendingPathComponent(file).path
更好,使用专用方法将URL路径传递给系统调用:
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)
}
这篇关于在Swift中将NSLog重定向到File无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!