skip to content

FileManager

FileManager is Foundation's API for the sandbox: finding Documents, Caches and temp folders, moving files, reading attributes. Interviewers ask where a file belongs, as that sets backup and eviction.

on this pageshow

explore

questions

6

With FileManager on iOS, how do you find your app's Documents directory, write a file there and read it back?

level: juniorimportance: must knowfreq 75%

answer

  1. the app's own sandbox container
  2. a search path in the user domain
  3. a static URL property since iOS 16
  4. Data's write(to:options:) and its initializer
  5. fileReadNoSuchFile when nothing is there

basics

~10 s

Every iOS app writes only inside its own sandbox container. Get Documents from URL.documentsDirectory (iOS 16) or FileManager.default.urls(for: .documentDirectory, in: .userDomainMask), append a file name, write with Data.write(to:options:) and read back with Data(contentsOf:).

solid answer

~40 s

An iOS app can write only inside its own sandbox container, and Documents is the folder in it for files the user creates. On iOS 16 and later `URL.documentsDirectory` returns it; for an older deployment target, `FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)` returns an array whose first element is the same folder. I build the file URL with `appending(path:)`, create any subfolder with `createDirectory(at:withIntermediateDirectories: true)`, write with `data.write(to: url, options: .atomic)` and read it back with `Data(contentsOf: url)`. Both calls throw, so I handle errors rather than checking `fileExists(atPath:)` first: a missing file surfaces as a `CocoaError` with code `fileReadNoSuchFile`. I never hardcode a container path, and I never write into `Bundle.main`, which is read-only on a device.

code

swift · 19 lines
swift
import Foundation

func saveScan(_ pdf: Data, named name: String) throws -> URL {
    let scans = URL.documentsDirectory.appending(path: "Scans", directoryHint: .isDirectory)
    try FileManager.default.createDirectory(at: scans, withIntermediateDirectories: true)
    let file = scans.appending(path: name)
    try pdf.write(to: file, options: .atomic)
    return file
}

func loadScan(named name: String) throws -> Data {
    let file = URL.documentsDirectory.appending(path: "Scans/\(name)")
    return try Data(contentsOf: file)
}

// Before iOS 16 there is no URL.documentsDirectory
func documentsDirectoryBeforeIOS16() -> URL {
    FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
}

go deeper

for a junior

Recall that the app can write only inside its sandbox, name both ways to get Documents and the iOS 16 line between them, and show a write and a read that both use try.

for a middle

Explain why the container path must be asked for rather than stored, what .atomic does during a write, and what createDirectory with intermediate directories does when the folder already exists.

for a senior

Show the review eye: hardcoded paths, writes into the bundle, check-then-act races around fileExists, and the error codes you match on instead of guessing why a read failed.

for a principal

Frame a small shared file-location helper the whole team calls, so no feature builds paths by hand and the pre-iOS 16 lookup can be deleted in one place when the deployment target moves.

## The sandbox container On iOS every app is installed into a **sandbox**: a private set of directories that only that app can read and write; sharing files with its own extensions goes through a separate App Group container. Two parts matter here: - The **bundle container** holds the signed app itself (`Bundle.main`). On a device it is read-only, so a downloaded or generated file can never be written next to the executable. - The **data container** holds the app's writable folders: `Documents`, `Library` (with `Application Support` and `Caches` inside it) and `tmp`. `Documents` is the folder for content the user creates and expects to keep, such as a scanned PDF. Choosing between `Documents`, `Application Support`, `Caches` and `tmp` for other kinds of files is a separate decision; this answer is about the mechanics of reaching one folder and using it. ## Finding the Documents directory The absolute path of the data container is decided by the system and contains an identifier you do not control, so you always ask Foundation for it instead of building a string. | API | Available from | Returns | |---|---|---| | `URL.documentsDirectory` | iOS 16 | the Documents folder as a `URL` | | `FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)` | iOS 4 | an array; on iOS its first element is the Documents folder | | `FileManager.default.url(for:in:appropriateFor:create:)` | iOS 4 | one `URL`, optionally creating the folder, and it throws | The iOS 16 static properties (`documentsDirectory`, `applicationSupportDirectory`, `cachesDirectory`, `temporaryDirectory`) are documented as equivalent to the older search-path lookup. Most apps still deploy back to iOS 17 or 18, where the static properties are available; an app that still supports iOS 15 needs the `urls(for:in:)` form. To build a file URL, use `appending(path:)` (iOS 16). The older `appendingPathComponent(_:)` and `URL.path` still work but are marked to be deprecated in favour of `appending(path:directoryHint:)` and `path(percentEncoded:)`. ## Writing and reading a file 1. Build the folder URL, for example `URL.documentsDirectory.appending(path: "Scans", directoryHint: .isDirectory)`. 2. Create it with `FileManager.default.createDirectory(at:withIntermediateDirectories: true)`. With `true` the call also creates missing parents and succeeds quietly when the folder already exists. 3. Write the bytes with `try data.write(to: fileURL, options: .atomic)`. The `.atomic` option writes to an auxiliary file first and then replaces the original, so a crash mid-write never leaves half a PDF behind. 4. Read them back with `try Data(contentsOf: fileURL)`. For text, `String(contentsOf:encoding:)` and `write(to:atomically:encoding:)` do the same job. To list what was saved, `contentsOfDirectory(at:includingPropertiesForKeys:options:)` returns the URLs in one folder, and `enumerator(at:includingPropertiesForKeys:options:errorHandler:)` walks subfolders. ## Handling errors instead of checking first `createDirectory`, the write, the read and `contentsOfDirectory` all `throw`. `Data(contentsOf:)` is not failable: when nothing exists at the URL it throws a `CocoaError` whose code is `fileReadNoSuchFile`. Checking `fileExists(atPath:)` before every read adds a second file-system call and still races with anything that deletes the file in between, so the usual shape is `do { try ... } catch CocoaError.fileReadNoSuchFile { ... }`. `fileExists(atPath:)` remains useful for a decision such as "is this the first launch with no scans yet". Three `CocoaError` codes cover most of what a file helper sees, and matching them by name keeps the handling honest: - `fileReadNoSuchFile` (260): a read found nothing at the URL. - `fileNoSuchFile` (4): `removeItem(at:)` was asked to delete something that is not there, or a parent folder is missing. - `fileWriteFileExists` (516): a move, copy or directory creation hit an item that already exists. Anything else, such as a full disk, is reported to the user rather than treated as a missing file. ## What goes wrong in review - A hardcoded path copied from a debugger session, such as a string that contains the container identifier. It works once and breaks on the next install. - A path built by concatenating `NSHomeDirectory()` and `"/Documents"` instead of asking for the directory URL. - Writing into `Bundle.main.bundleURL` or `Bundle.main.resourceURL`. On a device that write fails because the bundle is read-only; bundled seed files are copied into the data container on first launch instead. - Using `URL.documentsDirectory` in code that must still run on iOS 15 without an availability check. - A non-atomic write of a large file that a crash or a kill can cut short. The pattern is short: ask Foundation for the folder, create what is missing, write atomically, read with `try`, and let the thrown error tell you when a file is not there.

  • Why does writing a downloaded file into the app bundle fail on a device, and what do you do with files the app ships with?
    The bundle is the signed app itself and is read-only on a device, so any write into `Bundle.main.bundleURL` fails. Read shipped files with `Bundle.main.url(forResource:withExtension:)`. If the app must modify one, such as a starter database, copy it into Application Support on first launch with `copyItem(at:to:)` and work on the copy.
  • How do you list the scans saved under Documents/Scans with their sizes?
    Call `contentsOfDirectory(at:includingPropertiesForKeys:options:)` with keys such as `.fileSizeKey` and `.contentModificationDateKey` and the `.skipsHiddenFiles` option, then read each URL's `resourceValues(forKeys:)`. Passing the keys up front lets Foundation fetch those values with the listing. For nested folders, use `enumerator(at:includingPropertiesForKeys:options:errorHandler:)`.
  • When is fileExists(atPath:) the right call, and when is it a smell?
    It is fine for a decision that does not touch the file, such as showing an empty state when no scans folder exists yet. It is a smell as a guard before reading or writing: the file can change between the check and the call, and the read already throws `fileReadNoSuchFile`, so handling the error is shorter and race-free.

  • Hardcoding a container path copied from a debugger or Simulator session
  • Writing downloaded or generated files into the app bundle
  • Building the Documents path by appending a string to NSHomeDirectory()
  • Calling fileExists(atPath:) before every read instead of handling the thrown error
  • Using URL.documentsDirectory in code that still has to run on iOS 15
open as a page

With FileManager on iOS, where should a document-scanning app keep scanned PDFs, page thumbnails and a downloaded text-recognition model, and why?

level: middleimportance: must knowfreq 70%

basics

~20 s

Scanned 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.

open as a page

With FileManager on iOS, how does a scanning app share its latest scan with its share extension, and what breaks if misconfigured?

level: middleimportance: should knowfreq 45%

basics

~20 s

An app and its extension have separate sandboxes, so shared files live in an App Group container. Give both targets the same App Groups entitlement and call containerURL(forSecurityApplicationGroupIdentifier:), which returns nil on iOS for a wrong identifier.

open as a page

With FileManager on iOS, why does a scanning app's background task fail to read its scan index while the phone is locked, though the same read works with the app open?

level: seniorimportance: should knowfreq 30%

basics

~20 s

The index was written with FileProtectionType.complete, which makes a file unreadable while the device is locked. Files that locked-phone background work needs should use completeUntilFirstUserAuthentication, readable after the first unlock since boot, while user documents can stay complete.

open as a page

With FileManager on iOS, a scanning app saved each scan's absolute path in its database, and after an app update the scans seem gone: why, and what fixes it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

An iOS app's container path is not guaranteed to survive an update, reinstall or restore, so stored absolute paths name a folder that no longer exists. Store a base folder plus a relative path and rebuild the URL from URL.documentsDirectory.

open as a page

With FileManager on iOS, why does moveItem(at:to:) that installs a re-scanned PDF over the old one throw on every rescan, and how should the replacement be written?

level: seniorimportance: should knowfreq 40%

basics

~10 s

FileManager's moveItem(at:to:) and copyItem(at:to:) never overwrite: when an item already exists at the destination they stop and throw CocoaError.fileWriteFileExists. Replace a file with replaceItemAt(_:withItemAt:), or write the bytes with Data.write(to:options: .atomic).

open as a page