file deletion
document directory
file management
coding
programming

Delete specified file from document directory

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Deleting a file from the iOS documents directory is a normal FileManager operation, but it should still be done carefully. The important parts are locating the documents directory correctly, building the exact file URL you want to remove, and handling the case where the file is already missing or the operation fails.

Find the Documents Directory Correctly

In iOS, app-specific documents live in the user domain documents directory. Use FileManager.default.urls(for:in:) to retrieve it.

swift
1import Foundation
2
3func documentsDirectory() throws -> URL {
4    guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
5        throw NSError(domain: "FileError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Documents directory not found"])
6    }
7    return url
8}

Using a URL is safer than building file paths manually with string concatenation.

Build the Exact File URL

Once you have the directory, append the file name you want to remove.

swift
1import Foundation
2
3func fileURL(named fileName: String) throws -> URL {
4    try documentsDirectory().appendingPathComponent(fileName)
5}

For example, if the file is called notes.json, this gives you the full sandboxed file URL inside the app's document directory.

Delete the File with FileManager

The actual deletion call is removeItem(at:).

swift
1import Foundation
2
3func deleteFile(named fileName: String) throws {
4    let url = try fileURL(named: fileName)
5    try FileManager.default.removeItem(at: url)
6}

This will throw if the file does not exist or if the operation fails for another reason.

A Safer Version with Existence Check

In many apps, trying to delete a missing file should not be treated as a fatal error. Check first if that matches your use case.

swift
1import Foundation
2
3func deleteFileIfExists(named fileName: String) throws {
4    let url = try fileURL(named: fileName)
5
6    if FileManager.default.fileExists(atPath: url.path) {
7        try FileManager.default.removeItem(at: url)
8    }
9}

This makes repeated cleanup calls idempotent from the caller's perspective.

Full Runnable Example

This example creates a file, confirms it exists, deletes it, and then confirms removal.

swift
1import Foundation
2
3func documentsDirectory() throws -> URL {
4    guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
5        throw NSError(domain: "FileError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Documents directory not found"])
6    }
7    return url
8}
9
10func fileURL(named fileName: String) throws -> URL {
11    try documentsDirectory().appendingPathComponent(fileName)
12}
13
14func deleteFileIfExists(named fileName: String) throws {
15    let url = try fileURL(named: fileName)
16    if FileManager.default.fileExists(atPath: url.path) {
17        try FileManager.default.removeItem(at: url)
18    }
19}
20
21let demoURL = try fileURL(named: "demo.txt")
22try "temporary file".write(to: demoURL, atomically: true, encoding: .utf8)
23print(FileManager.default.fileExists(atPath: demoURL.path))
24
25try deleteFileIfExists(named: "demo.txt")
26print(FileManager.default.fileExists(atPath: demoURL.path))

This is useful for verifying the behavior in a small sandboxed test harness.

Working with Subdirectories

If your file lives in a subfolder under Documents, append each path component explicitly.

swift
let folderURL = try documentsDirectory().appendingPathComponent("Exports", isDirectory: true)
let fileURL = folderURL.appendingPathComponent("report.csv")

Deleting the correct file becomes much easier when your code treats URLs as structured paths instead of raw strings.

When to Use Documents Versus Cache

Not every file belongs in Documents. User-created or user-visible files usually do. Temporary or re-creatable files often belong in the caches directory instead.

Deleting from Documents should therefore reflect an intentional product rule, not just a generic cleanup habit.

Common Pitfalls

The most common mistake is building a raw string path manually instead of using directory URLs and appendingPathComponent. Another is calling removeItem without deciding whether a missing file is an error or a normal case. Teams also sometimes confuse the documents directory with the bundle, then try to delete files that are not writable at runtime. Finally, deleting files from the wrong sandbox location can appear to succeed in code review but fail silently in actual app behavior if the path calculation is wrong.

Summary

  • Use FileManager.default.urls(for:in:) to locate the documents directory.
  • Build file paths with URL methods, not string concatenation.
  • Use removeItem(at:) to delete the file.
  • Decide whether missing files should throw or be ignored.
  • Keep document-directory deletion intentional, because not all app files belong there.

Course illustration
Course illustration

All Rights Reserved.