URLSession is the built-in way to make network requests. With modern Swift you use async/await for clean asynchronous code.
A GET request
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)
}
Call it
Task {
do {
let user = try await fetchUser(id: 42)
// update UI on main actor
} catch {
print("Error: \(error)")
}
}
Common mistake: UI updates must happen on the main thread. Mark UI code with
@MainActor or dispatch to the main queue.Summary
URLSession + async/await fetches data simply. Decode JSON with Codable and always handle errors.