tezvyn:

URLSession data vs download vs upload tasks

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

choosing the right URLSession task.

OUTLINE

data tasks buffer responses in memory for small API calls; download tasks stream to a file and support background transfers for large files; upload tasks send bodies from data or files and report…

WHAT THIS TESTS This verifies you understand the practical differences among URLSession task types and the memory and background-execution implications that matter on a constrained mobile device.

A GOOD ANSWER COVERS A data task, URLSessionDataTask, accumulates the server response in memory and hands it back as Data, which is perfect for small, transient payloads like JSON API responses. Because it buffers everything in RAM, it is the wrong choice for large files. A download task, URLSessionDownloadTask, streams the response to a temporary file on disk, keeping memory flat regardless of file size, and supports resume data so an interrupted transfer can continue. Crucially, when used with a background URLSessionConfiguration, a download task can keep transferring even after the app is suspended or terminated, with the system relaunching the app on completion, which is essential for large media or podcasts. An upload task, URLSessionUploadTask, sends a request body from a Data object or, better for large content, a file URL, gives progress callbacks, and likewise supports background sessions. Choose data tasks for typical API calls, download tasks for fetching large files or anything needing background continuation, and upload tasks for sending files with progress.

COMMON WRONG ANSWERS Using a data task to fetch a large video, blowing up memory. Believing a data task can run in a background session, which it cannot. Confusing upload tasks with simply setting an httpBody on a data request.

LIKELY FOLLOW-UPS Why cannot data tasks run in background sessions? How does resume data work? When do you upload from a file versus Data? How does the system notify you when a background download finishes?

ONE CONCRETE EXAMPLE An app fetches a JSON feed with a data task because the payload is small and needed immediately in memory. To let users download a one-gigabyte offline video that finishes even if they background the app, it uses a download task on a background configuration, which writes to a temp file and relaunches the app on completion. Submitting a large user video to the server uses an upload task from a file URL to report progress without holding the whole file in RAM.

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.