With FileManager on iOS, where should a document-scanning app keep scanned PDFs, page thumbnails and a downloaded text-recognition model, and why?
answer
- who created it, and can it be rebuilt
- what the backup includes
- what the system may delete when storage is low
- Library has two folders worth knowing
- a resource value that opts a file out
basics
~20 sScanned PDFs go in Documents, which is backed up. Thumbnails go in Library/Caches, which is not backed up and may be emptied when storage is low. The model goes in Library/Application Support, marked isExcludedFromBackup because it can be downloaded again.
solid answer
~40 sI sort files by who made them and whether they can be rebuilt. The PDFs are the user's own work, so they go in `Documents`, which is included in backups. Thumbnails can be regenerated from the PDFs, so they go in `Library/Caches`: it is not backed up and the system may delete its contents when the device runs low on storage, so the app must cope with an empty folder. The text-recognition model is app data the app needs on every scan but can download again, so it goes in `Library/Application Support`, which I create with `createDirectory(at:withIntermediateDirectories: true)`, and I set `isExcludedFromBackup` through `URLResourceValues` so it does not inflate the user's backup. A half-finished export goes in `tmp` and is deleted when done.
code
swift · 17 linesimport Foundation
enum ScanStorage {
static let scans = URL.documentsDirectory.appending(path: "Scans", directoryHint: .isDirectory)
static let thumbnails = URL.cachesDirectory.appending(path: "Thumbnails", directoryHint: .isDirectory)
static let models = URL.applicationSupportDirectory.appending(path: "Models", directoryHint: .isDirectory)
static func installModel(_ data: Data, named name: String) throws -> URL {
try FileManager.default.createDirectory(at: models, withIntermediateDirectories: true)
var file = models.appending(path: name)
try data.write(to: file, options: .atomic)
var values = URLResourceValues()
values.isExcludedFromBackup = true
try file.setResourceValues(values) // again after every rewrite
return file
}
}go deeper
Recall the four folders and which ones the system may empty: Caches when storage is low, tmp when the app is not running. Documents is for what the user made.
Explain backup and purge for each folder, why Application Support must be created, and how isExcludedFromBackup is set through URLResourceValues on a var URL after the file exists.
Show the failure each wrong choice causes in production: bloated backups, a model that vanishes offline, lost scans under storage pressure, an exclusion flag silently reset by an atomic rewrite.
Turn the placement into a written rule per file kind, owned by one storage type in code, so new features inherit the right folder and backup flag instead of choosing ad hoc.
## Four folders, two questions An iOS app's data container has four places an app writes to. Two properties tell them apart: whether the folder is **included in the device backup**, and whether the **system may delete its contents** without asking. The folder you pick decides both, so the first question for any file is: did the user create it, and could the app rebuild it? | Folder | Swift lookup (iOS 16) | Backed up | System may delete it | Fits | |---|---|---|---|---| | `Documents` | `URL.documentsDirectory` | yes | no | files the user created and expects to keep | | `Library/Application Support` | `URL.applicationSupportDirectory` | yes, unless excluded | no | data the app needs and manages itself | | `Library/Caches` | `URL.cachesDirectory` | no | yes, when storage runs low | data the app can regenerate or download again | | `tmp` | `URL.temporaryDirectory` | no | yes, when the app is not running | files needed only for the current task | The SDK header itself calls `Library/Caches` "discardable cache files". Apple's guidance is that the system clears it when storage runs low and not while the app is running; it is also empty after a restore onto a new device, since it is not backed up. An app must treat every launch as possibly the morning after a purge. ## Placing the scanning app's files - **Scanned PDFs: `Documents`.** They are the user's work and cannot be recreated, so they belong where backups and device transfers carry them. If the app opts in through its Info.plist file-sharing keys, this is also the folder the Files app shows. - **Page thumbnails: `Library/Caches`.** They are derived from the PDFs. Losing them costs a little CPU on the next scroll, nothing more, and keeping them out of the backup saves the user's backup space. - **Text-recognition model: `Library/Application Support`.** The app needs it for every scan and may need it offline, so a folder the system can empty is a poor fit. It can be downloaded again, so it should not take up backup space either: set `isExcludedFromBackup` on it. - **An export being assembled: `tmp`.** Write it, hand it to the share sheet, then remove it with `removeItem(at:)`. ## Creating Application Support `Application Support` is not guaranteed to exist on a fresh install, so a write into it can fail until the app creates it. Two ways to make sure it does: 1. `try FileManager.default.createDirectory(at: modelsURL, withIntermediateDirectories: true)`, which creates every missing parent and succeeds quietly when the folder is already there. 2. `try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)`, which returns the folder and creates it when asked. ## Excluding a file from backup `isExcludedFromBackup` is a resource value on the file's `URL`, available since iOS 5.1: 1. Write the file first; the flag is set on an existing item. 2. Make a `var` copy of the URL, because `setResourceValues(_:)` is a `mutating` method. 3. Create `var values = URLResourceValues()`, set `values.isExcludedFromBackup = true`, and call `try url.setResourceValues(values)`. 4. Set it again after every rewrite. An `.atomic` write replaces the file with a new one, and the new file does not carry the old flag. Apple's documentation says the flag is meant for caches and other application support files, and that some common operations on user documents reset it to false, so it should not be used on user documents. That is one more reason the PDFs stay in `Documents` without it. The flag controls backups only. It does not stop the system purging a file, and it has nothing to do with encryption, which is the file's protection class. ## Common mistakes - Thumbnails or downloaded media in `Documents`, which bloats every backup with data the app could rebuild. - The model in `tmp` or `Caches`, which can vanish and force a large download just when the user is offline. - The user's scans in `Caches` because they are large, which risks losing irreplaceable files under storage pressure. - Assuming the exclusion flag survives an atomic rewrite. - A large model in Application Support without the exclusion flag, so hundreds of megabytes the app could download again ride along in every backup. - Files written by hand into `Library/Preferences`, the folder that holds the app's preference files, instead of one of the folders above. How big the thumbnail cache may grow and what it evicts first is cache design, covered with mobile memory and disk caches; the folder choice above is what FileManager itself decides.
- Why not keep the downloaded model in Library/Caches, since it can be downloaded again?Because the system may empty `Caches` when storage runs low, and the app needs the model for every scan, possibly offline. Losing it means a large download at the worst moment. `Application Support` keeps it until the app deletes it, and `isExcludedFromBackup` still keeps it out of the backup. The cost is that the app must remove old model versions itself.
- The app rewrites the model with Data.write(to:options: .atomic) after an update. What happens to its backup exclusion?An atomic write saves to an auxiliary file and swaps it in, so the item at that path is a new file and the exclusion reads back false. Set `isExcludedFromBackup` again after every rewrite, ideally inside the one helper that writes the model, so no call site forgets it.
- Should the app check free space before downloading the model?Yes. `resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])` on a URL in the container reports the space available for important resources, counting what purging caches could free. Compare it with the model's size before starting, and show a clear message instead of failing halfway through the write.
Documents is the client's filing cabinet that the movers always pack; Application Support is the office's own supply room, packed unless you tag a box as replaceable; Caches is the whiteboard the cleaner may wipe overnight; tmp is scratch paper you bin when the task is done.
- Putting regenerable thumbnails in Documents and bloating the user's backup
- Keeping the user's scans in Caches because the files are large
- Storing the downloaded model in tmp and expecting it to be there next week
- Assuming Application Support already exists on a fresh install
- Believing isExcludedFromBackup survives an atomic rewrite of the file
- Thinking isExcludedFromBackup also stops the system purging or encrypting the file