我有以下代码:
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=xyz")
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()
}
有时当我打电话给这个函数时,它打印出“货币不可用”)但有时候调用有效并转换货币。我可以确保如何确保呼叫不会失败?我甚至添加了延迟,以确保在拨打电话之前货币有足够的时间来获取。
编辑1:
好的,所以我删除了睡眠并添加了一个while循环,但声明
currency not available
在执行之前会被打印几乎200-300次,这实际上会导致应用程序在iPhone上崩溃。如何使用其他方法获得类似的结果。
func convert(currencyToConvert:String,amount:Double,currencyToConvertTo:String,date:String)->Double{
makeConnection(date: date)
var currencyFetched:Bool = false
var a:Double = 0.0
repeat {
if let x = currencyRates[currencyToConvert]{
if currencyToConvert == "USD"{
a = amount*currencyRates["SGD"]!
}
else {
a = (amount*currencyRates[currencyToConvertTo]!)/x
}
currencyFetched = true
print("currency available")
return a
}
else {
print("currency not available")
currencyFetched = false
}
}while currencyFetched == false
}
答案 0 :(得分:0)
线程睡眠不是一个好主意。而不是那样,你可以使用@escaping
闭包。
func convert(currencyToConvert:String ,amount:Double ,currencyToConvertTo:String ,date:String , completion: @escaping((Double?)->())){
currencyRates.removeAll()
let url = URL(string: "https://openexchangerates.org/api/historical/\(date).json?app_id=xyz")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
var result: Double?
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
}
if let x = currencyRates[currencyToConvert]{
if currencyToConvert == "USD"{
result = amount*currencyRates["SGD"]!
}
else {
result= (amount*currencyRates[currencyToConvertTo]!)/x
}
}
}
} catch {
}
}
completion(result)
}
task.resume()
}
最后使用:
convert(currencyToConvert: "",amount: 0.0,currencyToConvertTo: "",date:""){ value in
if let value = value{
// Use it here
}
}