TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Trying to create directory in documents folder fails

Forums > iOS

In my iOS app (running in the simulator) I'm able to create some files inside the documents directory with data.write(to: fileUrl) with fileUrl pointing to some file:///Users/Me/Library/Developer/CoreSimulator/..../Documents/myfile.xml.

Now I wanted to create a directory and store the files there (because I want to separate two different kinds of files I want to store), but a call to

try FileManager.default.createDirectory(atPath: pathUrl.absoluteString, withIntermediateDirectories: true)

with pathUrl being similar to the above file:///Users/Me/...../Documents/searches reveals

You can’t save the file “searches” because the volume is read only.

Couldn't find any additional information on what I would need to allow creating directories. Any idea?

Thanks Karsten

3      

Hi,

how are you creating the pathUrl? Because normally this should work without any extra steps.

This errors looks to me like you are trying to save it somewhere else than the Documens folder

3      

extension FileManager {
    /// Determine document directory.
    /// - Returns:a URL for the document directory.
    static func documentDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
}

let pathUrl = FileManager.documentDirectory().appendingPathComponent(path)
try FileManager.default.createDirectory(atPath: pathUrl.absoluteString, withIntermediateDirectories: false)

with path being a String, e.g. "searches".

Interesting fact is that the command throws an error with description:

The file “searches” doesn’t exist.

Yes, correct, that's why you should create it!

3      

@nemecek-filip, thanks for looking into it. It made me playing around with it again and triggering some new searches which lead me to: Instead of

try FileManager.default.createDirectory(atPath: pathUrl.absoluteString, withIntermediateDirectories: true)

use

try FileManager.default.createDirectory(atPath: pathUrl.path, withIntermediateDirectories: true)

which actually works. Thanks

3      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.