Download A Large File Without Holding It All In Memory
A download works perfectly with a small sample document. Then someone opens a 600 MB archive and the app’s memory graph climbs until the process disappears.
The first thing I would inspect is the shape of the networking API. If the next step needs a file, asking URLSession for a complete Data value gives the app a large allocation it never needed to own.
Choose the result you actually need
URLSession offers different ways to consume a response. data(for:) returns its body as data, bytes(for:) lets code consume an asynchronous byte sequence, and download(for:) returns the location of a downloaded temporary file. Apple’s async URLSession session demonstrates these different result shapes.
For an archive that will be passed to a file-based importer, a download is a useful starting point:
let (temporaryURL, response) = try await session.download(for: request)
This avoids collecting the complete response body into a Data value in your own loader. It does not promise that the networking stack uses no memory, or that the importer will be equally careful. Calling Data(contentsOf: temporaryURL) immediately afterward would bring the whole-file allocation back.
Use a byte stream when you need incremental interpretation, such as parsing a line-oriented feed. Do not build a byte-by-byte file writer just to recreate the disk-based download API.
Treat the temporary file as an unaccepted result
A completed transfer is not necessarily the asset you requested. An HTTP error can arrive with a perfectly downloadable HTML or JSON body. Move the result into your asset store only after the checks that make sense for that endpoint.
Here is a deliberately small acceptance function:
import Foundation
enum DownloadFailure: Error {
case unexpectedResponse
case unexpectedStatus(Int)
case exceedsSizeLimit
}
func adoptDownload(
at temporaryURL: URL,
response: URLResponse,
into directory: URL,
maximumBytes: Int64
) throws -> URL {
let files = FileManager.default
defer { try? files.removeItem(at: temporaryURL) }
guard let http = response as? HTTPURLResponse else {
throw DownloadFailure.unexpectedResponse
}
guard http.statusCode == 200 else {
throw DownloadFailure.unexpectedStatus(http.statusCode)
}
let attributes = try files.attributesOfItem(atPath: temporaryURL.path)
guard let size = attributes[.size] as? NSNumber,
size.int64Value <= maximumBytes
else {
throw DownloadFailure.exceedsSizeLimit
}
try Task.checkCancellation()
try files.createDirectory(at: directory, withIntermediateDirectories: true)
let destination = directory.appendingPathComponent(UUID().uuidString + ".bin")
try files.moveItem(at: temporaryURL, to: destination)
return destination
}
This endpoint expects a complete 200 response. A client that intentionally requests byte ranges needs a different acceptance contract; do not casually accept a partial 206 response as a complete asset.
The destination name is generated by the app. A server-provided filename can be useful display metadata, but it should not become an unchecked path inside your storage directory.
The defer removes rejected temporary data. After a successful move, the old location is already gone. In a production store, also record cleanup failures when they could leave substantial disk usage behind.
Finish ownership transfer before suspending again
Apple’s download guide explains that downloaded files initially live in temporary storage and need to be moved to a location your app manages. Make that ownership transfer a visible part of the loader:
actor DownloadStore {
private let session: URLSession
private let directory: URL
init(session: URLSession, directory: URL) {
self.session = session
self.directory = directory
}
func download(_ request: URLRequest, maximumBytes: Int64) async throws -> URL {
let (temporaryURL, response) = try await session.download(for: request)
return try adoptDownload(
at: temporaryURL,
response: response,
into: directory,
maximumBytes: maximumBytes
)
}
}
There is no unrelated await between receiving the temporary URL and adopting it. The actor holds the store’s configuration, while URLSession performs the transfer. The small synchronous acceptance step does not read the file contents into memory.
This function accepts the HTTP result and size only. An archive importer may additionally require a known format, a trusted manifest, a checksum, or limits on expanded content. Perform those checks before replacing the user’s currently working asset. A correctly downloaded corrupt archive is still corrupt.
A size check after downloading is not a transfer limit
The code checks the actual downloaded file size, which is useful for deciding whether to keep it. By the time that check runs, the bytes have already crossed the network and occupied temporary disk space.
If the product needs a strict download budget, add a transfer design that can cancel as bytes arrive. Expected content length is useful information, but it may be unknown and is not a substitute for counting received bytes. Cancellation also cannot promise that no additional buffered bytes arrive after the decision.
Pick a limit based on the feature. A 20 MB attachment and a multi-gigabyte offline map should not share an unexplained constant copied from an example.
Verify the file boundary separately from the network
The acceptance function is intentionally testable without a server. Give it a temporary file and a constructed HTTP response, then check successful adoption, rejection of an error body, rejection of an oversized result, and removal of rejected temporary files. Also check that a failed replacement leaves an earlier accepted asset intact.
After those deterministic checks, measure a real large transfer on a device. Watch peak memory, available disk space, cancellation, and the import step after the download. A small fixture cannot prove that a 600 MB workflow stays within a useful memory budget.
September 2026 review: the loader compiles with Swift 6.4 and Xcode 27. Executable file fixtures passed for successful moves, HTTP rejection, actual-size rejection, and temporary cleanup. Those checks do not exercise a live large download or background relaunch.
Finally, using a file-based result does not automatically make a transfer survive process termination. That is a separate background-session decision. Start by giving each layer the representation it needs: the networking layer writes a file, the store owns that file, and the importer consumes it without accidentally rebuilding the entire body in memory.