0Pricing
Swift Academy · Lesson

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

  1. URLSession data(from:) with async/await
  2. Codable: Encoding and Decoding JSON
  3. Error Handling and HTTP Status Codes
  4. Retry Logic and Background URLSession
← Back to Swift Academy