Skip to Content
Course content

81: Data Tasks, Download Tasks, Upload Tasks

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Look, I've seen this a dozen times in code reviews: a developer uses URLSessionDataTask for every single network request in their app. It works fine during development with small JSON payloads, but the moment the app hits production and tries to pull down a 100MB PDF or a high-res video, the app spikes in memory and the OS kills it. It's a classic trap.

"I can just save the Data object to a file manually"

The misconception is that a dataTask is the universal tool for receiving data, and if you need a file on disk, you just take the Data returned in the completion handler and write it using Data.write(to:).

Here is why that is dangerous. When you use a data task, the entire response is buffered into your device's RAM. If you're downloading a 500MB asset, your app is suddenly claiming 500MB of memory just to hold that blob before you even start writing it to the disk. On an iPhone, that's a great way to get a jetsam event (a memory-related crash). You aren't streaming the data; you're hoarding it.

Matching the Task to the Payload

To do this right, you have to choose the task based on how the data needs to live in memory. I usually break it down into these three scenarios:

  • Data Tasks: Use these for "small" things. API calls, JSON responses, or small images. These are meant for requests where the response is intended to be processed immediately in memory.
  • Download Tasks: Use these for anything that feels like a "file." These tasks stream the data directly to a temporary file on disk. Your app's memory footprint stays flat, regardless of whether the file is 1MB or 1GB.
  • Upload Tasks: Use these when sending files (like a photo or a log file) to a server. Like download tasks, these can be backed by a file on disk so you aren't loading a massive image into a Data object before sending it.
// The "Small Stuff" approach: Data Task
let url = URL(string: "https://api.example.com/user/profile")!
let dataTask = URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data else { return }
    // Perfect for JSON parsing
    let profile = try? JSONDecoder().decode(UserProfile.self, from: data)
}
dataTask.resume()

// The "Big Stuff" approach: Download Task
let fileURL = URL(string: "https://assets.example.com/huge-manual.pdf")!
let downloadTask = URLSession.shared.downloadTask(with: fileURL) { localURL, response, error in
    // localURL is a path to a temporary file on disk
    guard let localURL = localURL else { return }
    
    // You MUST move this file immediately, or the system deletes it
    let destinationURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        .appendingPathComponent("manual.pdf")
    
    try? FileManager.default.moveItem(at: localURL, to: destinationURL)
}
downloadTask.resume()

Handling Outbound Data without Memory Spikes

Upload tasks follow a similar logic to download tasks. If you're uploading a user's profile picture, a simple URLRequest with a httpBody (which is a data task) is usually fine. But if you're uploading a 4K video clip, you should use uploadTask(with:fromFile:).

By pointing URLSession to a file URL, the system can stream the bytes from the disk directly to the network interface. I've seen apps lag and stutter because they tried to convert a large video file into a Data object just to put it in a request body. Don't do that. Let the system handle the streaming.

// The professional way to upload a large file
var request = URLRequest(url: URL(string: "https://api.example.com/upload")!)
request.httpMethod = "POST"

let fileURL = URL(fileURLWithPath: "/path/to/video.mp4")
let uploadTask = URLSession.shared.uploadTask(with: request, fromFile: fileURL) { data, response, error in
    // Handle server confirmation
}
uploadTask.resume()



📋 Practical Task

Building a High-Resolution Asset Downloader

Your goal is to create a service that downloads a large sample file (you can use any large public PDF or image URL) without loading the entire file into RAM.

Requirements:

  • Implement a function downloadLargeAsset(from url: URL) that uses URLSessionDownloadTask.
  • Inside the completion handler, implement the logic to move the temporary file from the localURL provided by the system to the app's Documents directory.
  • Name the saved file "downloaded_asset.dat".
  • Add a print statement that outputs the final destination path of the file so you can verify it exists.
  • Ensure you handle the potential error thrown by FileManager.default.moveItem using a do-catch block.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.