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 String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.