Browse Questions
- Encapsulation, abstraction, inheritance, and polymorphism.
- All three create URLSessionTask subclasses but handle data differently.
- These four declarations differ in two dimensions: whether the array itself is optional, and whether the elements inside are optional.
- Wrap the request in a loop with a limited retry count.
Answer:
All three create URLSessionTask subclasses but handle data differently.
| Task | Best for | Data handling |
|---|---|---|
dataTask | API calls, small responses | In memory |
downloadTask | Files, large responses | Written to disk |
uploadTask | Sending files/data | Streams 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 }