Swift Async Network Request
Modern async/await pattern for making network requests in Swift.
asyncnetworkingapi
swift
func fetchData<T: Decodable>(from url: URL) async throws -> T {
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw NetworkError.invalidResponse
}
return try JSONDecoder().decode(T.self, from: data)
}
enum NetworkError: Error {
case invalidResponse
case decodingFailed
}