Advertisement
Guest User

Untitled

a guest
Dec 14th, 2020
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.23 KB | None | 0 0
  1. import Foundation
  2. import CoreLocation
  3.  
  4. //protocol NetworkWeatherManagerDelegate: class {
  5. //    func updateInterface(_: NetworkWeatherManager, with currentWeather: CurrentWeather)
  6. //}
  7.  
  8. class NetworkWeatherManager {
  9.    
  10.     enum RequestType {
  11.         case cityName(city: String)
  12.         case coordinate(latitude: CLLocationDegrees, longitude: CLLocationDegrees)
  13.     }
  14.    
  15.     var onCompletion: ((CurrentWeather) -> Void)?
  16.    
  17.     //weak var delegate: NetworkWeatherManagerDelegate?
  18.    
  19.     func fetchCurrentWeather(forRequestType requestType: RequestType) {
  20.         var urlString = ""
  21.         switch requestType {
  22.         case .cityName(let city):
  23.             urlString = "https://api.openweathermap.org/data/2.5/weather?q=\(city)&appid=\(apiKey)&units=metric"
  24.         case .coordinate(let latitude, let longitude):
  25.             urlString = "https://api.openweathermap.org/data/2.5/weather?lat=\(latitude)&lon=\(longitude)&appid=\(apiKey)&units=metric"
  26.         }
  27.         performRequest(withURLString: urlString)
  28.     }
  29.    
  30.     fileprivate func performRequest(withURLString urlString: String) {
  31.         guard let url = URL(string: urlString) else { return }
  32.         let session = URLSession(configuration: .default)
  33.         let task = session.dataTask(with: url) { data, response, error in
  34.             if let data = data {
  35.                 if let currentWeather = self.parseJSON(withData: data) {
  36.                     // self.delegate?.updateInterface(self, with: currentWeather)
  37.                     self.onCompletion?(currentWeather)
  38.                 }
  39.             }
  40.         }
  41.         // Для того чтобы таск начал работу, нужно сделать его resum
  42.         task.resume()
  43.     }
  44.    
  45.     fileprivate func parseJSON(withData data: Data) -> CurrentWeather? {
  46.         let decoder = JSONDecoder()
  47.         do {
  48.             let currentWeatherData = try decoder.decode(CurrentWeatherData.self, from: data)
  49.             guard let currentWeather = CurrentWeather(currentWeatherData: currentWeatherData) else { return nil
  50.             }
  51.             return currentWeather
  52.         } catch let error as NSError {
  53.             print(error.localizedDescription)
  54.         }
  55.         return nil
  56.     }
  57.    
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement