Why are my API Calls failing - Swift 3 : So I have the following code, 

     func convert(currencyToConvert:String,amount:Double,currencyToConvertTo:String,date:String)->Double{
        makeConnection(date: date)
        usleep(80000)
        if let x = currencyRates[currencyToConvert]{
            var a = 0.00
            if currencyToConvert == "USD"{
                a = amount*currencyRates["SGD"]!
            }
            else {
                a = (amount*currencyRates[currencyToConvertTo]!)/x
            }
            return a
        }
        else {
            print("currency not available")
            return 0.00
        }
        
    }
    
    func makeConnection(date:String){
        currencyRates.removeAll()
        
        let url = URL(string: "https://openexchangerates.org/api/historical/\(date).json?app_id=376fa06c3a104a21a0f94bd901a1e79f")
        
        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
            
            if error != nil
            {
                print ("ERROR")
                // ADD SEVERAL URL'S HERE FOR ACCESS HERE
            }
            else
            {
                if let content = data
                {
                    do
                    {
                        let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                        if let rates = myJson["rates"] as? NSDictionary
                        {
                            for (key, value) in rates
                            {
                                self.currencyRates[(key as? String)!] = value as? Double
                            }
                        }
                    }
                    catch
                    {
                        
                    }
                }
            }
        }
        task.resume()
    }

Sometimes when I make a call to this function it prints out "currency not available") but other times the call works and it converts the currency. What can I make sure to do so that the call doesn't fail? I have even added a delay to make sure that the currencies have enough time to fetch before the call is made. 