tezvyn:

FileManager: Your App's Interface to the File System

AI-drafted, machine-checkedSource: developer.apple.combeginner
FileManager: Your App's Interface to the File System

FileManager is your app's librarian for the file system. Instead of using raw paths, you ask it to find, create, or delete files and directories. Always handle potential errors, as file operations can easily fail.

WHY IT EXISTS Apps need a standard, safe way to interact with the device's file system without corrupting data or violating security sandboxes. FileManager provides this structured API, abstracting away the low-level details of different platforms like iOS and macOS.

THE MENTAL MODEL Think of FileManager as a helpful librarian for your app's dedicated section of the library, its sandbox. You don't go to the shelves yourself. You give requests to the librarian: "Please create a file for me in the Documents directory," or "Tell me if a file named 'config.json' exists in Caches." It handles the permissions and physical locations for you.

HOW IT WORKS You typically use the shared singleton instance, FileManager.default. You provide it with URLs pointing to file system locations. For example, to create a directory, you call createDirectory(at:withIntermediateDirectories:attributes:). To check for a file, you use fileExists(atPath:). Most modern methods are throwing, forcing you to handle potential errors like "permission denied" or "disk full" using a do-catch block.

WHEN TO USE IT Use it any time your app needs to persist data beyond its own runtime. This includes saving user-generated content to the Documents directory, storing downloaded data in the Caches directory, or reading bundled resources from your app's main bundle.

WHEN NOT TO USE IT For simple key-value storage of small data like user settings, UserDefaults is a better and simpler choice. For large, structured data, consider using a database like Core Data or SQLite directly, as they are more efficient for querying. Do not use FileManager for large I/O on the main thread, as it will freeze your UI.

ONE CANONICAL EXAMPLE A common task is saving a user's data. First, you get the URL for the app's Documents directory using FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!. Then you append a filename to that URL. Finally, you use a method like Data.write(to: options:) or FileManager's own createFile(atPath:contents:attributes:) to write the data to disk, wrapping the call in a do-catch block to handle errors.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.