Skip to content

Instantly share code, notes, and snippets.

@StewartLynch
Created July 14, 2021 04:49
Show Gist options
  • Save StewartLynch/3bf70ed93cd2de2b58fe19d128f2922d to your computer and use it in GitHub Desktop.
Save StewartLynch/3bf70ed93cd2de2b58fe19d128f2922d to your computer and use it in GitHub Desktop.
class APIService {
static let shared = APIService()
enum APIError: Error {
case error(_ errorString: String)
}
func getJSON<T: Decodable>(urlString: String,
dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate,
keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys,
completion: @escaping (Result<T,APIError>) -> Void) {
guard let url = URL(string: urlString) else {
completion(.failure(.error(NSLocalizedString("Error: Invalid URL", comment: ""))))
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
completion(.failure(.error("Error: \(error.localizedDescription)")))
return
}
guard let data = data else {
completion(.failure(.error(NSLocalizedString("Error: Data us corrupt.", comment: ""))))
return
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = dateDecodingStrategy
decoder.keyDecodingStrategy = keyDecodingStrategy
do {
let decodedData = try decoder.decode(T.self, from: data)
completion(.success(decodedData))
return
} catch let decodingError {
completion(.failure(APIError.error("Error: \(decodingError.localizedDescription)")))
return
}
}.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment