daily pastebin goal
68%
SHARE
TWEET

Untitled

a guest Jun 20th, 2018 47 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. struct CurrencyDataStore: Codable {
  2. var table: String
  3. var no : String
  4. var rates: [Currency]
  5.  
  6. enum CodingKeys: String, CodingKey {
  7.     case table
  8.     case no
  9.     case rates
  10. }
  11.  
  12. init(from decoder: Decoder) throws {
  13.  
  14.     let values = try decoder.container(keyedBy: CodingKeys.self)
  15.  
  16.     table = ((try values.decodeIfPresent(String.self, forKey: .table)))!
  17.     no = (try values.decodeIfPresent(String.self, forKey: .no))!
  18.     rates = (try values.decodeIfPresent([Currency].self, forKey: .rates))!
  19. } }
  20.  
  21. struct Currency: Codable {
  22. var currency: String
  23. var code: String
  24. var mid: Double
  25.  
  26. enum CodingKeys: String, CodingKey {
  27.     case currency
  28.     case code
  29.     case mid
  30. }
  31.  
  32. init(from decoder: Decoder) throws {
  33.     let values = try decoder.container(keyedBy: CodingKeys.self)
  34.  
  35.     currency = try values.decode(String.self, forKey: .currency)
  36.     code = try values.decode(String.self, forKey: .code)
  37.     mid = try values.decode(Double.self, forKey: .mid)
  38. }
  39. }
  40.    
  41. func getLatestRates(){
  42.     guard let currencyUrl = URL(string: nbpApiUrl) else {
  43.         return
  44.     }
  45.  
  46.     let request = URLRequest(url: currencyUrl)
  47.     let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
  48.  
  49.         if let error = error {
  50.             print(error)
  51.             return
  52.         }
  53.  
  54.         if let data = data {
  55.             self.currencies = self.parseJsonData(data: data)
  56.         }
  57.     })
  58.  
  59.     task.resume()
  60. }
  61.  
  62. func parseJsonData(data: Data) -> [Currency] {
  63.  
  64.     let decoder = JSONDecoder()
  65.  
  66.     do{
  67.         let currencies = try decoder.decode([String:CurrencyDataStore].self, from: data)
  68.  
  69.     }
  70.     catch {
  71.         print(error)
  72.     }
  73.     return currencies
  74. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top