Skip to content

Instantly share code, notes, and snippets.

@Myrrel
Created March 8, 2024 13:55
Show Gist options
  • Save Myrrel/76e353af98a4867672167ab4f0918974 to your computer and use it in GitHub Desktop.
Save Myrrel/76e353af98a4867672167ab4f0918974 to your computer and use it in GitHub Desktop.
fetchURLData with Generics
func fetchURLData<T: Decodable>(urlString: String, decodingType: T.Type) async throws -> T {
guard let url = URL(string: urlString) else {
throw URLError(.badURL)
}
let session = URLSession.shared
let (data, response) = try await session.data(from: url)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw URLError(.badServerResponse)
}
let decodedData = try JSONDecoder().decode(T.self, from: data)
return decodedData
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment