Skip to content

Instantly share code, notes, and snippets.

@myawesomehub
Last active August 17, 2021 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myawesomehub/36ce649f6c0052090161c312e9255ba5 to your computer and use it in GitHub Desktop.
Save myawesomehub/36ce649f6c0052090161c312e9255ba5 to your computer and use it in GitHub Desktop.
Enjoy !
enum NetworkError : Error {
case cityNotFound
case timeOut
}
class WeatherService {
static func getData(city : String , completionHandler : @escaping (Result<WeatherResponse, NetworkError>) -> ()) {
guard let url = URL(string: "\(city)") else {
return
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { data, response, error in
guard data != nil else {
completionHandler(.failure(NetworkError.timeOut))
return
}
do {
let decoder = JSONDecoder()
let decodedData = try decoder.decode(WeatherResponse.self, from: data!)
DispatchQueue.main.async {
completionHandler(.success(decodedData!))
}
} catch {
DispatchQueue.main.async {
completionHandler(.failure(NetworkError.cityNotFound))
}
}
}.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment