Created
March 8, 2024 13:55
-
-
Save Myrrel/76e353af98a4867672167ab4f0918974 to your computer and use it in GitHub Desktop.
fetchURLData with Generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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