URLSession data(from:) with async/await
Fetching data asynchronously from REST APIs using the modern URLSession API.
Modern URLSession API
Swift 5.5+ ships async overloads on URLSession: data(from:delegate:) that suspend instead of using callbacks.
let (data, response) = try await URLSession.shared.data(from: URL(string: "https://api.example.com/items")!)Full Fetch Function
Wrap the call in an async throwing function to make it composable and testable.
func fetchItems() async throws -> [Item] {
let url = URL(string: "https://api.example.com/items")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode([Item].self, from: data)
}All lessons in this course
- URLSession data(from:) with async/await
- Codable: Encoding and Decoding JSON
- Error Handling and HTTP Status Codes
- Retry Logic and Background URLSession