嗨,我是斯威夫特的新手,目前正在操场上玩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)
        }
    }
}

这是我在操场上的回报
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个价格。我有没有办法确保我的函数在这个循环中一致地打印出确切的价格?
多谢

最佳答案

您的游乐场在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/

10-12 00:25
查看更多