← All courses

Networking with URLSession

🗓 May 31, 2026 ⏱ 1 min read

Decodable models

struct User: Decodable {
    let id: Int
    let name: String
}

Fetching with async/await

func fetchUser(id: Int) async throws -> User {
    let url = URL(string: "https://api.example.com/users/\(id)")!
    let (data, _) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode(User.self, from: data)
}

Task {
    do {
        let user = try await fetchUser(id: 1)
        print(user.name)
    } catch {
        print("Error: \(error)")
    }
}
Tip: Always update the UI on the main thread. In SwiftUI, @MainActor and @Published handle this for you.