Skip to content

Instantly share code, notes, and snippets.

@soujohnreis
Last active September 24, 2021 13:14
Show Gist options
  • Save soujohnreis/f32809a34594e3ea34cd4518d5cc64e9 to your computer and use it in GitHub Desktop.
Save soujohnreis/f32809a34594e3ea34cd4518d5cc64e9 to your computer and use it in GitHub Desktop.
URLSession Decodable
enum URLError: Error {
case noData, decodingError
}
extension URLSession {
/// A type safe URL loader that either completes with success value or error with Error
func jsonDecodableTask<T: Decodable>(with url: URLRequest, decoder: JSONDecoder = JSONDecoder(), completion: @escaping (Result<T, Error>) -> Void) -> URLSessionDataTask {
self.dataTask(with: url) { (data, response, error) in
DispatchQueue.main.async {
guard error == nil else {
completion(.failure(error!))
return
}
guard let data = data, let _ = response else {
completion(.failure(URLError.noData))
return
}
do {
let decoded = try decoder.decode(T.self, from: data)
completion(.success(decoded))
} catch {
completion(.failure(error))
}
}
}
}
func jsonDecodableTask<T: Decodable>(with url: URL, decoder: JSONDecoder = JSONDecoder(), completion: @escaping (Result<T, Error>) -> Void) -> URLSessionDataTask {
self.jsonDecodableTask(with: URLRequest(url: url), decoder: decoder, completion: completion)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment