Skip to content

Instantly share code, notes, and snippets.

@thatswiftguy
Last active May 5, 2021 19:31
Show Gist options
  • Save thatswiftguy/363f2019e7d1ffb6aa6993b1a06ac1b1 to your computer and use it in GitHub Desktop.
Save thatswiftguy/363f2019e7d1ffb6aa6993b1a06ac1b1 to your computer and use it in GitHub Desktop.
import Foundation
class WeatherManager : ObservableObject {
@Published var tempText : Double = 0.0
@Published var conditionImage : Int = 0
@Published var cityName = ""
let weatherURL = "https://api.openweathermap.org/data/2.5/weather?appid={YOUR API KEY}&units=metric"
func fetchWeather(cityName : String){
let urlString = "\(weatherURL)&q=\(cityName)"
performRequest(with : urlString)
}
func performRequest(with urlString : String){
if let url = URL(string: urlString){
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url, completionHandler: handle(data:response:error:))
task.resume()
}
}
func handle(data : Data? , response : URLResponse? , error : Error?){
guard error == nil else {
print("Error while handling the request")
return
}
if let safeData = data {
if let weather = parseJSON(safeData){
DispatchQueue.main.async {
self.tempText = weather.main.temp
self.cityName = weather.name
self.conditionImage = weather.weather[0].id
}
}
}
}
func parseJSON(_ weatherData : Data) -> WeatherData? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
return decodedData
} catch {
print("Error while parsing")
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment