I'm trying to create a log.txt file inside a folder of a device, but I get this error:
NSCocoaErrorDomain Code=512 "The file “log.txt” couldn’t be saved in the folder “Logs”.
The folder Logs already exists on the device, but I still get this error. 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.
How can I solve this?
I have fixed this problem by using the new function called
appending(component:_)of theFileManagerAPI.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.