URLSessionDownloadTask: Download Files Without Hogging Memory

URLSessionDownloadTask downloads files directly to disk, not memory, making it ideal for large assets. Use it for videos or updates, especially in the background. The footgun: you must move the file from its temporary location or the OS will delete it.
WHY IT EXISTS Apps often need to download large files without crashing due to memory pressure. Holding a 500MB video file in memory is a recipe for disaster. URLSessionDownloadTask solves this by offloading the data directly to the device's disk, using it as a buffer instead of RAM.
THE MENTAL MODEL Think of URLSessionDownloadTask as a managed file transfer service. Instead of getting raw data chunks in memory like with a URLSessionDataTask, you tell the system "download this URL to a file." The OS handles the entire process, even in the background, and then hands you a temporary file path, saying, "Here's your file, move it somewhere safe before I clean up."
HOW IT WORKS You create a URLSessionDownloadTask with a URL. The system downloads the content to a temporary file in your app's sandbox, with progress reported via delegate methods. Upon completion, the urlSession(_:downloadTask:didFinishDownloadingTo:) delegate method is called, providing a URL to this temporary file. Your code must then use FileManager to move or copy this file to a permanent location (like the Documents directory) before the delegate method returns. If you fail to move it, the temporary file is deleted automatically. The task also supports pausing and resuming: call cancel(byProducingResumeData:) to get a data blob that you can use to create a new task and continue the download later.
WHEN TO USE IT Use it for any network resource that is too large to comfortably fit in memory. This is the standard for downloading files like videos, audio archives, or software updates. It is essential for downloads that need to continue if the user backgrounds the app.
WHEN NOT TO USE IT For small API responses like JSON or XML, a URLSessionDataTask is simpler and more efficient. Using a download task for a few kilobytes of data is overkill, as it involves unnecessary file I/O when keeping the data in memory is perfectly safe and straightforward.
ONE CANONICAL EXAMPLE A podcast app downloads a new episode. It creates a URLSessionDownloadTask for the MP3 file. The user can leave the app, and the download continues. When finished, the app's delegate moves the temporary MP3 file into a permanent "Episodes" folder, making it available for offline listening.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.