嗨,我是 swift 的新手,目前正在通过在 Playground 中使用来自 cryptocompare 的 API 来学习 json 和 API,秒的速率限制为每秒 15 秒, 我没有在我的循环中获得期望的返回量
这是我的代码
func getPrice(coinSymbol: String, currency: String, day: Date,
completion: @escaping (Double?) -> Void) {
let baseURL = URL(string: "https://min-api.cryptocompare.com/data/dayAvg")!
let query: [String: String] = ["fsym": coinSymbol, "tsym": currency, "toTs": String(format:"%.0f", day.timeIntervalSince1970)]
let url = baseURL.withQueries(query)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let data = data,
let rawJSON = try? JSONSerialization.jsonObject(with: data), //convert data into native swift values
let json = rawJSON as? [String: Any]{
if let price = json[currency] as? Double {
completion(price)
} else {
print("price not found")
}
} else {
print("Either no data was returned or data was not serialised.")
return
}
}
task.resume()
}
//lastMonth is an Array, [Date] with count of 31
for day in lastMonth {
getPrice(coinSymbol: "BTC", currency: "USD", day: day) { (price) in
if let price = price {
print(price)
}
}
}
这是我在 Playground 的归来
6738.16
6253.38
6346.16
6588.89
6705.49
.
.
.
price not found
price not found
8248.19
price not found
price not found
price not found
price not found
price not found
7572.14
7406.26
6998.43
7151.93
6993.97
每次刷新都会打印不同数量的价格,但我很少能得到我想要的 31 价格。无论如何,我是否可以确保我的函数在此循环中始终如一地打印出准确的价格金额?
非常感谢
最佳答案
您的 playground 在 for 循环后完成执行,并且不会等待所有异步请求返回。您需要手动等待它们,如下所示:
let group = DispatchGroup()
for day in lastMonth {
group.enter()
getPrice(coinSymbol: "BTC", currency: "USD", day: day) { (price) in
if let price = price {
print(price)
}
group.leave()
}
}
group.notify(queue: DispatchQueue.main) {
print("done")
exit(0)
}
dispatchMain()
关于json - Swift 函数在循环时不一致地返回 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51730703/