MM
Size: a a a
MM
MM
AT
MM
A
𝙰
AO
M
CoreLocation
import Foundation
public
final
class WeatherCervice:NSObject{
private
let locationManager = CLLocationManager()
private
let API_KEY = "229f5f60c0ce797df9f3b6093ea45ee3"
private
var completionHandler: ((Weather)-> Void)?
public
override
init(){
super.init()
locationManager.delegate =
self
}
public
func loadWeatherData(
_ completionHandler:
@escaping@escaping((Weather)-> Void)) {
self.completionHandler = completionHandler
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
// https://api.openweathermap.org/data/2.5/find?lat={lat}&lon={lon}&cnt={cnt}&appid={API key}
private
func makeDataResponce(forCoordinates coordinates: CLLocationCoordinate2D){
guard
let urlString = "https://api.openweathermap.org/data/2.5/find?lat=\(coordinates.latitude)&lon=\(coordinates.longitude)&appid=\(API_KEY)&units=metric"
.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
else {
return }
print("UrlString")
guard
let url = URL(string: urlString)
else {
return}
print("URL")
URLSession.shared.dataTask(with: url) { data , response , error
in
print("3")
guard error ==
nil,
let data = data
else{
return}
print("2")
if
let response =
try? JSONDecoder().decode(APIResponse.
self, from: data){
print("1")
self.completionHandler?(Weather(response: response))
}
}
.resume()
}
}
extension WeatherCervice: CLLocationManagerDelegate{
public
func locationManager(
_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]){
guard
let location = locations.first
else {
return}
print("Got location")
makeDataResponce(forCoordinates: location.coordinate)
}
public func locationManager(_ manager:CLLocationManager,M
M
MM
MM
IB
IB
MM
𝙰