iOS File System

iOS File System

Every iOS application operates within its own highly secure "Sandbox."

This sandboxed file system prevents your app from directly accessing files belonging to other apps or the core operating system.

Understanding the specific folders within your sandbox is essential for properly storing documents, caches, and temporary files.


The Sandbox Directories

When your app is installed, iOS creates several specific directories for you to use. The three most important are:

  1. Documents Directory: Used for user-generated content that cannot be recreated (e.g., custom drawings, text files). This folder is backed up to iCloud automatically.
  2. Caches Directory: Used for data that can be downloaded or generated again easily (e.g., downloaded profile images). iOS may delete this folder without warning to free up space.
  3. Temporary Directory (tmp): Used for very short-lived files. You should delete files here when you are done, or iOS will clean them out periodically.

Using FileManager

The FileManager class provides the API for navigating these directories and manipulating files.

Locating the Caches Directory:

import Foundation

func getCachesDirectory() -> URL { // We ask FileManager for the Caches directory path let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) return paths[0] }

print("Caches path: \(getCachesDirectory().path)")


Checking if a File Exists

Before attempting to read a file, or to avoid overwriting an existing one, you should check if it exists.

FileManager provides a simple method to verify paths.

Checking File Existence:

import Foundation

func checkIfFileExists(filename: String) { let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileURL = documents.appendingPathComponent(filename) if FileManager.default.fileExists(atPath: fileURL.path) { print("The file is ready to be opened.") } else { print("File not found!") } }


Creating Directories

If your app generates a lot of files, you should organize them into subfolders rather than dumping them all in the root Documents directory.

Creating a Subfolder:

import Foundation

func createImagesFolder() { let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let folderURL = documents.appendingPathComponent("DownloadedImages") do { // withIntermediateDirectories: true will create parent folders if needed try FileManager.default.createDirectory(at: folderURL, withIntermediateDirectories: true, attributes: nil) print("Folder created successfully!") } catch { print("Error creating folder: \(error.localizedDescription)") } }


Exercise

Which directory is automatically backed up to iCloud and should be used for irreplaceable, user-generated content?