Introduction
\nWorking with the file system is one of the key tasks when developing applications for iOS and macOS. Whether you are writing an app to save user data, cache images, or export documents, understanding the basics of working with files in Swift is an essential skill. In this article, we will cover practical examples of working with the file system: creating, reading, writing, deleting files, and managing directories.
\nApple provides a powerful API FileManager that allows you to interact with the file system on both iOS and macOS. We will explore it with real-world examples and ready-to-use code.
1. Getting Paths to System Directories
\nBefore starting to work with files, you need to access the correct directories. In iOS and macOS, each application runs in an isolated sandbox. Use the following paths for storing data:
\n\nDocuments Directory
\nUsed for storing user data that should persist across app updates and backups.
\nimport Foundation\n\nfunc getDocumentsDirectory() -> URL {\n let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)\n return paths[0]\n}\n\n// Example usage\nlet documentsURL = getDocumentsDirectory()\nprint("Documents path: \\(documentsURL.path)")\n\nCaches Directory
\nFor temporary files that can be recreated (e.g., image cache).
\nfunc getCachesDirectory() -> URL {\n let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)\n return paths[0]\n}\n\nLibrary/Application Support Directory
\nFor storing data that should not be directly accessible to the user but should persist.
\nfunc getApplicationSupportDirectory() -> URL {\n let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)\n let directory = paths[0]\n // Ensure the directory exists\n try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)\n return directory\n}\n\n2. Creating and Writing Files
\nNow that we know where to store files, let's learn how to create them and write data.
\n\nWriting Text Data
\nThe simplest way is to use the write(to:) method on a String or Data.
func writeTextFile() {\n let fileName = "example.txt"\n let documentsURL = getDocumentsDirectory()\n let fileURL = documentsURL.appendingPathComponent(fileName)\n \n let content = "Hello, Swift! This is a test file."\n \n do {\n try content.write(to: fileURL, atomically: true, encoding: .utf8)\n print("File successfully created: \\(fileURL.path)")\n } catch {\n print("Error writing file: \\(error.localizedDescription)")\n }\n}\n\nWriting Binary Data (Images, JSON)
\nFor working with binary data, use Data.
func writeJSONFile() {\n let fileName = "data.json"\n let documentsURL = getDocumentsDirectory()\n let fileURL = documentsURL.appendingPathComponent(fileName)\n \n let dictionary: [String: Any] = [\n "name": "Swift Developer",\n "age": 30,\n "skills": ["iOS", "macOS", "SwiftUI"]\n ]\n \n do {\n let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)\n try jsonData.write(to: fileURL, options: .atomic)\n print("JSON file saved")\n } catch {\n print("Error: \\(error)")\n }\n}\n\nCreating Directories
\nSometimes you need to create nested folders to organize files.
\nfunc createSubdirectories() {\n let documentsURL = getDocumentsDirectory()\n let subDirURL = documentsURL.appendingPathCo