[英]Text file can't be created inside a folder
I'm trying to create a log.txt
file inside a folder of a device, but I get this error:我正在尝试在设备的文件夹内创建一个
log.txt
文件,但出现此错误:
NSCocoaErrorDomain Code=512 "The file “log.txt” couldn't be saved in the folder “Logs”.
NSCocoaErrorDomain Code=512 “文件“log.txt”无法保存在文件夹“Logs”中。
The folder Logs
already exists on the device, but I still get this error.设备上已存在
Logs
文件夹,但我仍然收到此错误。 Please find my code below:请在下面找到我的代码:
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let logPath = path.appendingPathComponent("Logs").appendingPathComponent("log.txt")
try! "Hello world".write(to: logPath, atomically: true, encoding: .utf8)
However, if I replace the logPath
with path.appendingPathComponent("log.txt")
, it will work, BUT it creates the file outside of the folder Logs
instead of inside.但是,如果我将
logPath
替换为path.appendingPathComponent("log.txt")
,它会起作用,但它会在文件夹Logs
外部而不是内部创建文件。
How can I solve this?我该如何解决这个问题?
I have fixed this problem by using the new function called appending(component:_)
of the FileManager
API.我通过使用
FileManager
API 的名为 appending appending(component:_)
的新 function 解决了这个问题。
The old one that I used in my question was not deprecated, but it did not work, and I still have no idea.我在问题中使用的旧版本并没有被弃用,但它没有用,我仍然不知道。
However, using the new one above makes everything works just fine.但是,使用上面的新版本可以使一切正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.