json - Swift 函数在循环时不一致地返回 API 调用

标签 json swift api loops asynchronous

嗨,我是 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/

相关文章:

javascript - 如何使用 JQuery 使用循环插入 JSON 数据中的图像?

ios - 为什么我无法保存应用内购买?

java - HTTP 从 API 获取 XML 请求

javascript - 动态添加数组元素到 JSON 对象

javascript - 使用ajax成功函数中的json对象(使用angularjs)

ios - 带有 URL 的 UITableViewCell

ios - 如何在 Swift 的核心数据中保存多个项目

ruby-on-rails - 循环访问来自 Flickr 的 API 结果

api - 使用子域对 REST API 进行版本控制

java - 在Java中使用JSONata抛出异常