iOS
file writing
mobile development
iOS app development
Swift programming

Write a file on iOS

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Writing a file on iOS usually comes down to three decisions: which sandbox directory to use, whether you are writing text or binary data, and how you want to handle errors. The actual API surface is small once those choices are clear.

In modern iOS code, FileManager, String.write, and Data.write cover most file-writing tasks. The harder part is choosing the right location so the file behaves correctly with backup, caching, and app restarts.

Choose the right sandbox directory

Every iOS app runs in its own sandbox. You cannot write arbitrary files anywhere on the device, only inside directories your app owns.

The most common choices are:

  • 'Documents for user-generated or user-visible files'
  • 'Library/Application Support for internal app data that should persist'
  • 'Library/Caches for data that can be recreated'
  • 'tmp for short-lived temporary files'

If the file should survive app launches and matter to the user, Documents is usually correct. If it is internal state, Application Support is often better.

Write a text file with String.write

For simple text output, use String.write. First, build the destination URL from FileManager.

swift
1import Foundation
2
3let fileManager = FileManager.default
4let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
5let fileURL = documentsURL.appendingPathComponent("notes.txt")
6
7let text = "Hello from iOS\n"
8
9do {
10    try text.write(to: fileURL, atomically: true, encoding: .utf8)
11    print("Saved to \(fileURL.path)")
12} catch {
13    print("Write failed: \(error)")
14}

This creates or overwrites notes.txt in the app's Documents directory. The atomically flag writes to a temporary file first and then swaps it into place, which reduces the risk of leaving a partially written file behind.

Write binary data with Data.write

If you are saving JSON bytes, images, or custom binary content, write Data instead of String.

swift
1import Foundation
2
3struct Settings: Codable {
4    let username: String
5    let notificationsEnabled: Bool
6}
7
8let settings = Settings(username: "ada", notificationsEnabled: true)
9let data = try JSONEncoder().encode(settings)
10
11let appSupportURL = try FileManager.default.url(
12    for: .applicationSupportDirectory,
13    in: .userDomainMask,
14    appropriateFor: nil,
15    create: true
16)
17
18let fileURL = appSupportURL.appendingPathComponent("settings.json")
19try data.write(to: fileURL)

This pattern is common for app preferences, cached API responses, and offline state.

Create directories before writing nested files

If your destination lives inside a subdirectory, create that folder first:

swift
1import Foundation
2
3let baseURL = try FileManager.default.url(
4    for: .applicationSupportDirectory,
5    in: .userDomainMask,
6    appropriateFor: nil,
7    create: true
8)
9
10let reportsURL = baseURL.appendingPathComponent("Reports", isDirectory: true)
11try FileManager.default.createDirectory(
12    at: reportsURL,
13    withIntermediateDirectories: true
14)
15
16let reportURL = reportsURL.appendingPathComponent("summary.txt")
17try "Daily report".write(to: reportURL, atomically: true, encoding: .utf8)

Without that directory creation step, the write fails because the parent folder does not exist.

Think about backup and privacy

Where you write the file affects system behavior. Files in Documents and much of Library may be backed up. Cache files and temporary files may be deleted by the system when space is needed.

For sensitive files, the sandbox alone may not be enough. iOS data protection, Keychain storage, or encryption may be more appropriate depending on what the file contains.

Common Pitfalls

  • Saving internal cache-like data in Documents and causing unnecessary user-facing persistence or backups.
  • Building file paths as raw strings instead of using URL and FileManager.
  • Forgetting to create parent directories before writing nested files.
  • Doing large or repeated file I/O on the main thread and stalling the UI.
  • Treating sandboxing alone as enough protection for sensitive data that may need stronger storage controls.

Summary

  • Use the app sandbox and choose the directory based on the file's purpose.
  • 'String.write is convenient for text files, while Data.write is better for binary or encoded content.'
  • Build file paths with URL, not manual string concatenation.
  • Create parent directories before writing nested files.
  • Treat backup, caching, and privacy as part of the file-writing decision, not as afterthoughts.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.