You are building an iOS app and need to make a network request. Explain how to do this using URLSession. Please what is URLSession, show a simple example of using URLSession.shared.dataTask to fetch data from a URL, how do you handle the response? Explain the (data, response, error) tuple in the completion handler, and how does this integrate with modern Swift concurrency using async/await? Show an example using URLSession.shared.data(from:).
Assistant
We are building an iOS app and need to make a network request. We are to explain how to do this using URLSession.
We must cover:
What is URLSession?
Show a simple example of using URLSession.shared.dataTask to fetch data from a URL.
How to handle the response? Explain the (data, response, error) tuple in the completion handler.
How does this integrate with modern Swift concurrency using async/await? Show an example using URLSession.shared.data(from:).
Let's break it down step by step.
What is URLSession?
URLSession is Apple's core networking API for iOS, macOS, watchOS, and tvOS. It's responsible for making HTTP/HTTPS requests and handling responses. Key features:
Manages network connections, caching, authentication, and cookies
Supports background transfers, uploads/downloads, and WebSocket connections
Thread-safe and designed for asynchronous operations
Integrates with Swift concurrency (async/await)
Traditional Completion Handler Approach
Simple Example with URLSession.shared.dataTask
swift
import Foundation
// Basic GET request example
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
// 1. Handle network errors first
if let error = error {
print("Network error: \(error.localizedDescription)")
return
}
// 2. Check HTTP response status
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print("Invalid response or status code")
return
}
// 3. Verify data exists
guard let data = data else {
print("No data received")
return
}
// 4. Process data (example: parse JSON)
do {
let todo = try JSONDecoder().decode(Todo.self, from: data)
print("Title: \(todo.title)")
} catch {
print("JSON parsing error: \(error)")
}
}
task.resume() // ⚠️ MUST CALL to start the request
Understanding the Completion Handler Tuple
The (data, response, error) tuple provides three pieces of information:
Parameter
Type
Purpose
Typical Use
data
Data?
Raw response bytes
Parse JSON/XML, convert to image
response
URLResponse?
Metadata about response
Check status code, headers
error
Error?
Network-level errors
Timeouts, connectivity issues
Key Handling Pattern:
Error-first check - If error != nil, request failed at network level
Validate response - Cast to HTTPURLResponse and check status code (200-299 = success)
Validate data - Ensure data != nil before parsing
Process data - Convert Data to usable format (JSON, image, etc.)
import Foundation
// Define a Codable model
struct Todo: Codable {
let userId: Int
let id: Int
let title: String
let completed: Bool
}
// Async function using async/await
func fetchTodo() async throws -> Todo {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else {
throw URLError(.badURL)
}
do {
// Suspends until response arrives or error occurs
let (data, response) = try await URLSession.shared.data(from: url)
// Validate HTTP response
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
throw URLError(.badServerResponse)
}
// Decode JSON
return try JSONDecoder().decode(Todo.self, from: data)
} catch {
// Handles both network errors and thrown errors above
print("Request failed: \(error)")
throw error
}
}
// Usage from an async context (e.g., SwiftUI view model, async function)
@MainActor
class ViewModel: ObservableObject {
@Published var todo: Todo?
@Published var errorMessage: String?
func loadTodo() {
Task {
do {
todo = try await fetchTodo()
} catch {
errorMessage = error.localizedDescription
}
}
}
}
Key Differences from Completion Handlers
Aspect
Completion Handler
async/await
Readability
Nested closures, "callback hell"
Linear, top-down flow
Error Handling
Manual checks in closure
try/throw syntax
Threading
Must dispatch to main manually
Automatically resumes on original actor
Control Flow
Hard to break early
Natural return, throw, loops
Tuple
3-tuple (data, response, error)
2-tuple (data, response) - errors thrown
Important Considerations
1. Threading & UI Updates
URLSession callbacks happen on background threads
Traditional: Use DispatchQueue.main.async for UI updates
Async/await: If calling from @MainActor context, UI updates work automatically
swift
// Traditional approach for UI update
URLSession.shared.dataTask(with: url) { data, _, _ in
DispatchQueue.main.async {
self.image = UIImage(data: data!)
}
}.resume()
// Async/await - no manual dispatch needed from @MainActor
@MainActor
func loadImage() async {
let (data, _) = try await URLSession.shared.data(from: url)
self.image = UIImage(data: data)
}
2. Cancellation
swift
// Traditional
let task = URLSession.shared.dataTask(...)
task.resume()
task.cancel() // Cancel anytime
// Async/await - use Task
let task = Task {
let todo = try await fetchTodo()
}
task.cancel() // Cancels the async operation
3. Configuration Options
swift
// Custom session for special requirements
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 30
config.requestCachePolicy = .reloadIgnoringLocalCacheData
let session = URLSession(configuration: config)
// Use `session.dataTask(...)` instead of shared
4. Error Types to Handle
URLError (network connectivity, timeouts)
HTTPURLResponse status codes (404, 500, etc.)
DecodingError (JSON parsing failures)
NSError with custom domains
Best Practices Summary
Always validate - Check errors, status codes, and data existence
Use async/await for new code (iOS 15+)
Handle cancellation - Clean up resources if requests are cancelled
Consider security - Use HTTPS, handle App Transport Security exceptions if needed
Test edge cases - No internet, slow network, server errors, malformed data
The async/await approach is strongly recommended for new development as it produces cleaner, more maintainable code with proper error handling semantics that match Swift's language design.