我试图将NSLog发送到在模拟器,IOS 10.2上运行的Swift 3中的文件,并且没有生成任何内容
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")
}
Run Code Online (Sandbox Code Playgroud)
产量
~/Library/Developer/CoreSimulator/Devices/A7B717-3ED8-493A-9778-C594AF9FF446/data/Containers/Data/Application/B0386-64BB-46EB-9BF2-65209FC748CD/Documents/file.txt
Run Code Online (Sandbox Code Playgroud)
唯一的影响是输出不再打印到控制台.
我试过了
freopen(logPath.cString(using: .utf8), "a+", stderr)
Run Code Online (Sandbox Code Playgroud)
以及其他各种组合
使用我收到的路径写入文件没有问题,所以没有任何问题
我希望在路径中看到一个名为file.txt的文件,并且该文件包含"print nslog".我尝试先创建文件但没有成功.
a的absoluteString属性URL产生URL字符串,例如
file:///path/to/file.txt
这不适合作为参数freopen().要将文件路径作为字符串,请path改为使用:
let logPath = dir.appendingPathComponent(file).path
Run Code Online (Sandbox Code Playgroud)
更好的是,使用专用方法将URL路径传递给系统调用:
let logFileURL = dir.appendingPathComponent(file)
logFileURL.withUnsafeFileSystemRepresentation {
_ = freopen($0, "a+", stderr)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1099 次 |
| 最近记录: |