-
-
Save haikusw/aa6070a8d415be0bdf00279e2b089dd8 to your computer and use it in GitHub Desktop.
This file contains 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
// A URLSession extension that fetches data from a URL and decodes to some Decodable type. | |
// Usage: let user = try await URLSession.shared.decode(UserData.self, from: someURL) | |
// Note: this requires Swift 5.5. | |
extension URLSession { | |
func decode<T: Decodable>( | |
_ type: T.Type, | |
from url: URL, | |
keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, | |
dataDecodingStrategy: JSONDecoder.DataDecodingStrategy = .deferredToData, | |
dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate | |
) async throws -> T { | |
let (data, _) = try await data(from: url) | |
let decoder = JSONDecoder() | |
decoder.keyDecodingStrategy = keyDecodingStrategy | |
decoder.dataDecodingStrategy = dataDecodingStrategy | |
decoder.dateDecodingStrategy = dateDecodingStrategy | |
let decoded = try decoder.decode(T.self, from: data) | |
return decoded | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment