eranseg

JSON Exresice

May 13th, 2020
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 5.63 KB | None | 0 0
  1. //-----  CityWeatherTableViewController.swift --------
  2. import UIKit
  3.  
  4. class CityWeatherTableViewController: UITableViewController {
  5.  
  6.     @IBOutlet weak var weatherDataTableView: UITableView!
  7.    
  8.     let cellReuseIdentifier = "CityPropCellReuseIdentifier"
  9.     let citiesList: [String] = ["Holon", "Paris", "London", "Malaga", "Madrid", "Zanzibar", "Istanbul", "Roma", "Berlin", "Moscow"]
  10.    
  11.     struct position {
  12.         var city: String
  13.         var description: String
  14.         var temp: String
  15.         var humidity: String
  16.         var windSpeed: String
  17.     }
  18.     let myAPIkey:String = "e726b53e902ebe807d746eb96ffc01b7"
  19.     var citiesProps:[position] = []
  20.    
  21.     var myURL:String = ""
  22.    
  23.     override func viewDidLoad() {
  24.         super.viewDidLoad()
  25.         title = "City Weather"
  26.         navigationController?.navigationBar.prefersLargeTitles = true
  27.         setDelegates()
  28.         getCitiesWeatherProps()
  29.     }
  30.  
  31.     fileprivate func getCitiesWeatherProps() {
  32.         for city in citiesList {
  33.             getCityWeatherData(city: city)
  34.         }
  35.         print(citiesProps)
  36.     }
  37.    
  38.     fileprivate func getCityWeatherData(city: String) {
  39.         myURL = "https://api.openweathermap.org/data/2.5/weather?q=\(city)&appid=\(myAPIkey)"
  40.         //convert our string to URL
  41.          let url = URL(string: myURL)!
  42.         var newPos: position?
  43.          //create a url async task
  44.          URLSession.shared.dataTask(with: url){
  45.              (data,response,error) in
  46.              //check  if we  not have error, and if we have, print the error
  47.              if error != nil {
  48.                  let myError = error! as NSError
  49.                  print (myError)
  50.              } else {
  51.                  do {
  52.                     let parseData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
  53.                     let currentWeather = parseData!["weather"] as! NSArray
  54.                     let currentWeatherData = currentWeather[0] as! [String:Any]
  55.                     let currentDescription = currentWeatherData["description"]  as! String
  56.                     let currentMainData = parseData!["main"] as! [String:Any]
  57.                     var currentTemperature = currentMainData["temp"]  as! Double
  58.                     let currentHumidity = ((currentMainData["humidity"]  as! Double) * 1000).rounded(.toNearestOrEven) / 1000
  59.                     let currentWindData = parseData!["wind"] as! [String:Any]
  60.                     let currentWindSpeed = ((currentWindData["speed"]  as! Double) * 1000).rounded(.toNearestOrEven) / 1000
  61.                     newPos = position(city: city, description: currentDescription, temp: String(currentTemperature.f2c()), humidity: String(currentHumidity), windSpeed: String(currentWindSpeed))
  62.                     print(newPos!)
  63.                     print("a")
  64.                     self.citiesProps.append(newPos!)
  65.                     DispatchQueue.main.async {
  66.                         self.weatherDataTableView.reloadData()
  67.                     }
  68.                  } catch let error as NSError {
  69.                      print (error)
  70.                  }
  71.              }
  72.          }.resume()
  73.     }
  74.    
  75.     fileprivate func setDelegates() {
  76.         weatherDataTableView.delegate = self
  77.         weatherDataTableView.dataSource = self
  78.     }
  79.  
  80.     // MARK: - Table view data source
  81.  
  82.     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  83.         return citiesProps.count
  84.     }
  85.  
  86.     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  87.         let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! WeatherInfoTableViewCell
  88.         print(9)
  89.         cell.cityNameLabel.text = citiesProps[indexPath.row].city
  90.         cell.humidityLabel.text = citiesProps[indexPath.row].humidity
  91.         cell.tempLabel.text = citiesProps[indexPath.row].temp
  92.         cell.weatherDescriptionLabel.text = citiesProps[indexPath.row].description
  93.         cell.windSpeedLabel.text = citiesProps[indexPath.row].windSpeed
  94.         switch citiesProps[indexPath.row].description {
  95.         case "broken clouds":
  96.             cell.backgroundColor = .systemGray
  97.         case "scattered clouds":
  98.             cell.backgroundColor = .systemGray2
  99.         case "overcast clouds":
  100.             cell.backgroundColor = .systemGray3
  101.         case "light rain":
  102.             cell.backgroundColor = .systemBlue
  103.         case "clear sky":
  104.             cell.backgroundColor = .systemTeal
  105.         default:
  106.             cell.backgroundColor = .systemPink
  107.         }
  108.         return cell
  109.     }
  110.    
  111.     override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  112.         return 200
  113.     }
  114.    
  115. }
  116.  
  117. extension Double{
  118.     mutating func f2c() -> Double{
  119.         var x: Double
  120.         x = (5000*(self-32))/9
  121.         return x.rounded(.toNearestOrEven) / 1000
  122.     }
  123. }
  124.  
  125. // ----------- WeatherInfoTableViewCell.swift --------
  126.  
  127. import UIKit
  128.  
  129. class WeatherInfoTableViewCell: UITableViewCell {
  130.    
  131.     @IBOutlet var cityNameLabel: UILabel! = UILabel()
  132.     @IBOutlet var weatherDescriptionLabel: UILabel! = UILabel()
  133.     @IBOutlet var tempLabel: UILabel! = UILabel()
  134.     @IBOutlet var humidityLabel: UILabel! = UILabel()
  135.     @IBOutlet var windSpeedLabel: UILabel! = UILabel()
  136.    
  137.     override func awakeFromNib() {
  138.         super.awakeFromNib()
  139.         // Initialization code
  140.     }
  141.  
  142.     override func setSelected(_ selected: Bool, animated: Bool) {
  143.         super.setSelected(selected, animated: animated)
  144.  
  145.         // Configure the view for the selected state
  146.     }
  147.  
  148. }
Add Comment
Please, Sign In to add comment