Why this happens
When an app downloads content after an in-app purchase, it typically stores files in the app’s Documents directory. Developers often need to verify a file exists before loading it—falling back to a default if missing. The confusion arises because Bundle.main only accesses read-only resources shipped with the app, not user-generated or downloaded content. The Documents directory lives in the app’s sandbox under ~/Documents and requires FileManager to reach.
A secondary issue is the race condition inherent in check-then-act patterns. Between the moment fileExists(atPath:) returns true and the moment you open the file, another process (or a malicious actor) could delete, replace, or change permissions on that file. Apple’s Secure Coding Guide explicitly warns against predicating behavior on file-system state checks.
How to fix it
1. Standard existence check with FileManager (Swift)
This is the direct answer for most use cases. Get the Documents directory URL, append your filename, and call fileExists(atPath:).
import Foundation
func htmlFileExists(named filename: String) -> Bool {
let fileManager = FileManager.default
guard let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
return false
}
let fileURL = documentsURL.appendingPathComponent(filename)
return fileManager.fileExists(atPath: fileURL.path)
}
// Usage
if htmlFileExists(named: "purchased.html") {
// load purchased.html
} else {
// load default.html
}
Key points:
– urls(for:in:) returns an array; the first element is the Documents directory.
– appendingPathComponent is safe for path construction.
– fileExists(atPath:) expects a String path, hence .path on the URL.
2. Objective-C equivalent
If you maintain legacy Objective-C code:
- (BOOL)htmlFileExistsNamed:(NSString *)filename {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if (paths.count == 0) return NO;
NSString *documentsPath = paths[0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:filename];
return [[NSFileManager defaultManager] fileExistsAtPath:filePath];
}
3. Safer pattern: try to open and handle the error
Apple recommends attempting the operation directly and catching the error. This eliminates the time-of-check-to-time-of-use (TOCTOU) race window.
func loadHTMLFile(named filename: String) -> String? {
let fileManager = FileManager.default
guard let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
return nil
}
let fileURL = documentsURL.appendingPathComponent(filename)
do {
let htmlString = try String(contentsOf: fileURL, encoding: .utf8)
return htmlString
} catch CocoaError.fileReadNoSuchFile {
// File doesn't exist — fall back to default
return nil
} catch {
// Other errors (permissions, corruption, etc.)
print("Failed to read \(filename): \(error)")
return nil
}
}
// Usage
let html = loadHTMLFile(named: "purchased.html") ?? loadDefaultHTML()
Why this is better:
– Single system call; no gap between check and use.
– Handles permissions, corruption, and missing files uniformly.
– Cleaner control flow—no separate boolean branch.
4. Checking with FileManager attributes (bonus)
If you also need metadata (size, modification date) without opening the file:
func fileAttributes(for filename: String) -> [FileAttributeKey: Any]? {
let fileManager = FileManager.default
guard let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
return nil
}
let fileURL = documentsURL.appendingPathComponent(filename)
return try? fileManager.attributesOfItem(atPath: fileURL.path)
}
How to prevent it
- Default to try-open: Use the
do-catchpattern (Fix #3) for any file you intend to read immediately. - Avoid
try!: The accepted answer usestry!onurl(for:in:appropriateFor:create:). In production, handle the error—directory creation can fail on low disk space or permission changes. - Sanitize filenames: User-supplied or server-provided filenames can contain path traversal sequences (
../). Validate or sanitize before appending. - Use
FileManager.default: Reuse the singleton instead of creating newFileManager()instances. - Test on device: The Simulator’s Documents path differs from a real device; always verify on hardware.
FAQ
Does fileExists(atPath:) work for directories too?
Yes. It returns true for both files and directories. To distinguish, use attributesOfItem(atPath:) and check FileAttributeKey.type for FileAttributeType.typeDirectory.
Why does my Documents path return nil in unit tests?
Unit test targets run in a different sandbox. In tests, inject a FileManager protocol or use a temporary directory via FileManager.default.temporaryDirectory for deterministic behavior.
Can I list all HTML files in Documents instead of checking one by one?
Yes. Use FileManager.default.contentsOfDirectory(at:includingPropertiesForKeys:options:) on the Documents URL, then filter by path extension html. This is more efficient when you need to present a list of downloaded purchases.
func downloadedHTMLFiles() -> [URL] {
let fileManager = FileManager.default
guard let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
return []
}
let allFiles = (try? fileManager.contentsOfDirectory(at: documentsURL,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles)) ?? []
return allFiles.filter { $0.pathExtension.lowercased() == "html" }
}
Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.