Read/Write to the local FS

Is there a reliable safe way to read/write to a location in the local FS using a simulator and in the future a real device? The recommended way I found using

FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

creates a new Application directory every time I run a simulator

There are a few reasons why I would like to use local FS:

  • To avoid Firebase access for testing
  • Ability to cache data while there is no connectivity for the actual app
  • For demo purposes

But regardless of why, is there a reliable way to have persistent storage in local FS?

I use this to get a persistent documents directory on simulator and device for iOS.

FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

I think that doesn't work on tvOS though, I ended up using UserDefaults to store the data I needed to store and .cachesDirectory to store files in the filesystem that would be available every run.

FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

When I use this code, I see a new Application directory name (just a random UUID) that exists after completion and is deleted when I run it next time with a new random UUID generated.

FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

Could there be anything wrong, do I need to use any additional settings?

I guess you build+run and observing it in Xcode's console. Note that if you run the app "normally" (from the springboard) the directory won't change, unless you reinstall the app or "reset settings" with "erase contents" option.

This is normal. The debugger does that to encourage developers not to store full paths. You should use the APIs to get the path or url to the various directories within your app sandbox. The paths can change when an app is updated from the appstore and possibly other times. I usually use the Application Support folder for files that are intended to be long-lived and not visible to the user.