Keep Temporary Files From Becoming Permanent Storage
The export finishes, the share sheet closes, and the app appears done. A month later, Settings reports several gigabytes of documents and data. Each export left behind a folder that nobody owned after the happy path returned.
Temporary storage needs a lifetime policy just as much as an in-memory cache. The filesystem does not know when your last consumer has finished reading a generated file.
Give one operation one workspace
For intermediate files whose entire lifetime fits inside an asynchronous operation, use a scoped directory:
import Foundation
func withScratchDirectory<Value: Sendable>(
under root: URL,
cleanupFailed: @Sendable (any Error) -> Void,
operation: @Sendable (URL) async throws -> Value
) async throws -> Value {
try Task.checkCancellation()
let directory = root.appendingPathComponent(UUID().uuidString, isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer {
do { try FileManager.default.removeItem(at: directory) } catch { cleanupFailed(error) }
}
return try await operation(directory)
}
Pass an app-owned scratch root, such as a dedicated subdirectory of FileManager.default.temporaryDirectory. Each operation receives a unique child, so concurrent exports cannot overwrite each other’s output.mov or delete a sibling’s work.
The cleanup runs when the operation returns or throws. cleanupFailed lets the app record a cleanup problem without replacing the original export error. Log a job identifier and error category; a private user filename does not need to appear in every diagnostic.
This is an ownership convention, not a type-system guarantee. The closure can return a URL, but that URL points into a directory removed as the function exits. Return a value you have already consumed, or move a final artifact into a separately owned location before returning.
Await the last reader
This sequence is too short:
// Conceptual example of a lifetime bug:
// create file → start sharing → return → delete file
Presenting a share sheet is not the same event as its consumer finishing. A renderer, uploader, or share integration might still be reading the URL after your function returns. Keep the workspace alive until that API’s documented completion point, or transfer the output to an owner with the appropriate longer lifetime.
The same rule applies to unstructured tasks. Starting a Task inside the closure and returning before it finishes lets the cleanup race the task’s file access. Await work that belongs to this scope. For background uploads, use the durable job’s file retention policy instead of a short-lived scratch scope.
Do not depend on a purge schedule
Apple’s disk-usage guidance describes temporary and cache storage as purgeable. Neither location is a reliable home for the only copy of user-created work. The filesystem guide also makes the app responsible for deleting temporary files it no longer needs.
That gives us two separate requirements: tolerate missing disposable files, and remove our own files promptly. “The OS will eventually clean this up” satisfies neither a predictable storage budget nor a pending upload’s durability needs.
Choose the directory from the data’s purpose. Disposable intermediate frames belong in scratch storage. A reproducible preview can live in a cache. A user-created attachment waiting for a reliable upload needs storage and recovery rules that survive the workflow’s interruptions.
Recover from work that never unwound
defer runs when Swift exits the scope normally through a return or throw. A killed process does not get to execute your cleanup code. Give orphan cleanup its own small startup or maintenance pass.
Only inspect the feature’s dedicated scratch root. Never recursively empty the entire system temporary directory. If the workspace is shared with an extension or background work, consult the persisted job owner before deleting anything. A file’s old modification date is not proof that no reader is using it.
A useful cleanup plan classifies folders as active, recoverable, or disposable. Put a byte budget and a bounded amount of work on the cleanup pass, record failures, and try again later. Keep deletion decisions out of a SwiftUI view’s onDisappear; navigation changes are not a storage lifecycle.
Verify the exceptional path
Test a successful operation that returns consumed content, then one that creates a partial file and throws. Both should leave the scratch root without their child directories. Also test two simultaneous operations so finishing one cannot delete the other.
September 2026 review: the Swift 6.4 fixture passed cleanup after a successful return and after a thrown cancellation error. It does not simulate process termination or an external share consumer; those require integration checks in the app.
The useful question is not just “where do I write this file?” It is “who can prove the last reader is finished?” Once that owner is explicit, cleanup becomes part of the feature instead of a hopeful timer.