2021-05-27

Currency JSON File Format Change

I have a currency exchange app that parses exchange rates received from the web. Recently the JSON file format changed to now include the date. It changed from this:

{
    "usd": {
        "aed": 4.420217,
        "afn": 93.3213,
        "all": 123.104693,
        "amd": 628.026474,
        "ang": 2.159569,
        "aoa": 791.552347,
        "ars": 111.887966,
        "aud": 1.558363,
        "awg": 2.164862,
        "azn": 2.045728,
        "bam": 1.9541,
        "bbd": 2.429065,
        "bch": 0.001278
    }
}

to this:

{
    "date": "2021-05-26",
    "usd": {
        "aed": 4.420217,
        "afn": 93.3213,
        "all": 123.104693,
        "amd": 628.026474,
        "ang": 2.159569,
        "aoa": 791.552347,
        "ars": 111.887966,
        "aud": 1.558363,
        "awg": 2.164862,
        "azn": 2.045728,
        "bam": 1.9541,
        "bbd": 2.429065,
        "bch": 0.001278
    }
}

The code that follows is the version that doesn't support the date. I believe the only things I need to change are the formats of base and getCurrencies in the class GetCurrency. It also seems like I need to add "let date: String" after the "let id = UUID()" line. But I haven't had much luck so far get things to work with the date.

class GetCurrency: Codable {
    
    let id = UUID()
    
    var getCurrencies: [String : [String: Double]] = [:]
    required public init(from decoder: Decoder) throws {
        do{
            let baseContainer = try decoder.singleValueContainer()
            let base = try baseContainer.decode([String : [String: Double]].self)
            
            for key in base.keys{
                getCurrencies[key] = base[key]
            }
        }catch{
            print(error)
            throw error
        }
    }
}


class CurrencyViewModel: ObservableObject{
    
    @Published var results: GetCurrency?
    @Published var rateArray = [Double] ()
    
    init() {
        if UserDefaults.standard.array(forKey: "rates") != nil {
            rateArray = UserDefaults.standard.array(forKey: "rates") as! [Double]
    } else {
        rateArray = [Double] (repeating: 0.0, count: 170)
        UserDefaults.standard.set(self.rateArray, forKey: "rates")
        }
    }


func updateRates(baseCur: String) {
        
        var currencyCode: String = ""
        
        let baseUrl = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/"
        let requestType = ".json"
        
        guard let url = URL(string: baseUrl + baseCur + requestType) else {
            print("Invalid URL")
            return
        }
        let request = URLRequest(url: url)
        print(url)
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                do{
                    let decodedResponse = try JSONDecoder().decode(GetCurrency.self, from: data)
                    
                    DispatchQueue.main.async {
                        self.results = decodedResponse
                        
                        //print(self.results?.getCurrencies[baseCur]?.values ?? 0.0)
                        
                        // loop through all available currencies
                        for index in 0..<currCode.count {
                            currencyCode = currCode[index]
                            
                            // spacial handling for base currency
                            if currencyCode == baseCur {
                                self.rateArray[index] = 1.0000
                            } else {
                                
                                let homeRate = self.results?.getCurrencies[baseCur]
                                if let unwrapped = homeRate?[currencyCode] {
                                    self.rateArray[index] = 1.0 / unwrapped
                                } else {
                                    print("Invalid working exchange rate dictonary lookup")
                                }
                            }
                        }
                        UserDefaults.standard.set(self.rateArray, forKey: "rates")
                    }
                } catch {
                    //Error thrown by a try
                    print(error)
                }
            }
            if error != nil {
                //data task error
                print(error!)
            }
        }.resume()
    }
}


from Recent Questions - Stack Overflow https://ift.tt/3fRblPI
https://ift.tt/eA8V8J

No comments:

Post a Comment