NetworkingMidMCQ

What is the difference between `dataTask`, `downloadTask`, and `uploadTask`?

Test your knowledge:

Explanation & Code

Answer: All three create URLSessionTask subclasses but handle data differently.

TaskBest forData handling
dataTaskAPI calls, small responsesIn memory
downloadTaskFiles, large responsesWritten to disk
uploadTaskSending files/dataStreams from memory or file

Code Example:

// dataTask — API response stays in memory
URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data else { return }
    let user = try? JSONDecoder().decode(User.self, from: data)
}

// downloadTask — saves to temp file, survives memory pressure
URLSession.shared.downloadTask(with: url) { tempURL, response, error in
    guard let tempURL = tempURL else { return }
    let dest = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    try? FileManager.default.moveItem(at: tempURL, to: dest.appendingPathComponent("video.mp4"))
}

// uploadTask — send a file
var request = URLRequest(url: uploadURL)
request.httpMethod = "POST"
URLSession.shared.uploadTask(with: request, fromFile: fileURL) { data, response, error in }

Rate your understanding:

Ready to practice more Networking?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.