Advertisement
Larme

Untitled

Apr 19th, 2021
1,350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.02 KB | None | 0 0
  1. import UIKit
  2.  
  3. class HomeViewController: UIViewController {
  4.    
  5.     var covidStatData: CovidStat?
  6.    
  7.     override func viewDidLoad() {
  8.         super.viewDidLoad()
  9.         print("viewDidLoad(): covidStatData before getCovidStat(): \(covidStatData)")
  10.         getCovidStat()
  11.         print("viewDidLoad(): covidStatData after getCovidStat(): \(covidStatData)")
  12.     }
  13.    
  14.    
  15.     func getCovidStatJSON(completion: @escaping (String?, Error?) -> Void) {
  16.         print("getCovidStatJSON(completion:) start")
  17.         let zipCd = User.currentUser?.zipCd
  18.         let apiURL: String = "https://localcoviddata.com/covid19/v1/locations?zipCode=\(zipCd ?? "")"
  19.         guard let cURL = URL(string: apiURL) else { return }
  20.         let request = URLRequest(url: cURL)
  21.         URLSession.shared.dataTask(with: request) { (data, response, error) in
  22.             print("dataTask(with:) closure")
  23.             if let str = String(data: data!, encoding: .utf8) {
  24.                 completion(str, nil)
  25.             }
  26.         }.resume()
  27.         print("getCovidStatJSON(completion:) end")
  28.     }
  29.    
  30.     func getCovidStat() {
  31.         print("getCovidStat start")
  32.         getCovidStatJSON(completion: { covidStatJSON, error in
  33.             print("getCovidStatJSON(completion:) closure")
  34.             if let covidStatJSON = covidStatJSON {
  35.                 let covidStatData = Data(covidStatJSON.utf8)
  36.                 let decoder = JSONDecoder()
  37.                 do {
  38.                     print("Will set covidStatData")
  39.                     self.covidStatData = try decoder.decode(CovidStat.self, from: covidStatData)
  40.                     print("Did set covidStatData")
  41.                     //Now that we set the value, let's use it
  42.                     DispatchQueue.main.async {
  43.                         //self.myLabel.text = self.covidStatData.zipCd
  44.                         //...
  45.                     }
  46.                 } catch {
  47.                     print(error)
  48.                 }
  49.  
  50.             }
  51.         })
  52.         print("getCovidStat end")
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement