Skip to content

Instantly share code, notes, and snippets.

@adirburke
Created August 25, 2020 03:51
Show Gist options
  • Save adirburke/7b9cf946f3d58150498adde13c8e61d9 to your computer and use it in GitHub Desktop.
Save adirburke/7b9cf946f3d58150498adde13c8e61d9 to your computer and use it in GitHub Desktop.
//
// main.swift
// weatherAPIcall
//
// Created by Adir Burke on 25/8/20.
// Copyright © 2020 WorkDesk. All rights reserved.
//
import Foundation
// MARK :- Models
struct WeatherResponse : Codable {
let main : MainResponse
}
struct MainResponse : Codable {
let temp : Double
let feelsLike : Double
let tempMin: Double
let tempMax: Double
let pressure: Double
let humidity: Double
}
// MARK :- API Request
func fetchWeather(url : URL) -> WeatherResponse? {
let semaphore = DispatchSemaphore(value: 0)
var result : WeatherResponse? = nil
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if let error = error {
print("Error with fetching: \(error)")
semaphore.signal()
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print("Error with the response, unexpected status code: \(response)")
semaphore.signal()
return
}
if let data = data {
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let weatherResponse = try decoder.decode(WeatherResponse.self, from: data)
result = weatherResponse
} catch {
print(error)
}
}
semaphore.signal()
})
task.resume()
semaphore.wait()
return result
}
// MARK :- Main
let APIKey = "XXXXXXX"
let city = "London"
guard var url2 = URLComponents(string: "https://api.openweathermap.org/data/2.5/weather") else { fatalError() }
url2.queryItems = [ .init(name: "q", value: city),
.init(name: "appid", value: APIKey),
.init(name: "units", value: "metric")]
guard let url = url2.url else { fatalError() }
guard let response = fetchWeather(url: url) else { fatalError() }
print("Current temp in \(city) is \(response.main.temp)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment