Last active
August 17, 2021 04:30
-
-
Save thatswiftguy/36ce649f6c0052090161c312e9255ba5 to your computer and use it in GitHub Desktop.
Enjoy !
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
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