1

I am trying to write data on the device. But I don't want them to be public to the user and want to save them in a custom reposity. I tried this code

let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("test/mytest")
print(fileURL)
try data?.write(to: fileURL)

this is the obtained path

file:///var/mobile/Containers/Data/Application/34567-234567dfgh-dfghj/Documents/test/mytest

But I get an error telling me that mytest could not be found in folder test

0

1 Answer 1

2

You have to create the directory first before you call write:

FileManager.default.fileExists(atPath: fileURL)
var isDir: ObjCBool = ObjCBool(false)
let exists = FileManager.default.fileExists(atPath: fileURL, isDirectory: &isDir)
if !exists && !isDir.boolValue {
    try! FileManager.default.createDirectory(at url: fileURL, withIntermediateDirectories: true)
}

Although when you call url(for:in:appropriateFor:create:), you passed true to create:, the directory /test/mytest is not created because you appended it. So, you have to create it.

Sign up to request clarification or add additional context in comments.

4 Comments

This means that with this solution the directory will be re-created each time I want to write a new file, so old files will be destroyed?
You create a directory only if the said directory does not exist. You can check if directory exists using FileManager.default.fileExists(atPath: fullPath, isDirectory:&isDir)
@user567 added a check
The code in this answer is wrong. This code only attempts to create the directory if it already exists and if it is already a directory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.