- Swifty Snippets
- Posts
- Store SwiftData in Application Support
Store SwiftData in Application Support
Don't store SwiftData in the documents directory
There is a misconception that your persistent storage of SwiftData or CoreData should go in the documents directory. This is incorrect as files in the documents directory are easily viewable by users. A user should not have direct access to the persistent storage.
But remember, the only things that should be going into the Documents directory are files that will make sense to people using your app. The critical question you should ask is, "Should my users be able to see this file?" If the answer is yes, then that's fine. But if the answer is no, move it out of the Documents directory and into one of the following locations. The Application Support directory is a good place to store files that might be in your Documents directory but that shouldn't be seen by users. For example, a database that your app needs but that the user would never open manually.
As suggested by Apple, Application Support is a much better location.
let databaseURL = URL.applicationSupportDirectory
.appending(path: "Database.sqlite")
let configuration = ModelConfiguration(url: databaseURL)
Hacking With Swift shows example code that uses the documents directory. I sent Paul an email on 25/02/24 encouraging him to change this.