gpt4 book ai didi

swift - 如何处理alamofire的异步?

转载 作者:行者123 更新时间:2023-11-30 11:50:39 25 4
gpt4 key购买 nike

我正在尝试保存从 JSON fire 获得的数据,但是,由于 Alamofire 的异步特性,我无法立即获得所需的数据,而是只有当我再次点击 tableviewcell 时才获得(并且数据也是错误的)

我想知道我应该在这里做什么,以便当我点击 tableviewcell 时它将获得我需要的数据(而不是空数组)

这是我的代码:

class CurrencyExchangeViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

let exchange = currencyExchangeModel()
var past30DaysDateValueToPass = [String]()
var past30DaysPriceValueToPass = [Double]()
var valueToPass = ""



func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath) as? CurrencyExchangeTableViewCell
valueToPass = Array(self.exchange.currencyToGetExchangesDictionary.keys)[indexPath.row]
self.getPastData(currency: valueToPass)
performSegue(withIdentifier: "currencyHistorySegue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "currencyHistorySegue") {
var viewController = segue.destination as? CurrencyHistoricalDataViewController
viewController?.historicalCurrency = valueToPass
viewController?.past30DaysPrice = self.exchange.currencyPast30DaysPriceArray
viewController?.past30DaysDate = self.exchange.currencyPast30DaysDatesArray
}
}

func getPastData(currency: String){
Alamofire.request("https://api.coindesk.com/v1/bpi/historical/close.json?currency=\(currency)").responseJSON{ (responseData) in
if responseData.result.value != nil {
let responseJSON = JSON(responseData.result.value)["bpi"].dictionaryObject
self.exchange.currencyPast30DaysDatesArray = Array(responseJSON!.keys)
self.exchange.currencyPast30DaysPriceArray = Array(responseJSON!.values) as! [Double]
}
}

}
}

最佳答案

如果您希望在从 Alamofire 获取数据后执行 performSegue 则删除

 performSegue(withIdentifier: "currencyHistorySegue", sender: self)

此行来自 didselect 并放置在 getPastData 处。

func getPastData(currency: String){
Alamofire.request("https://api.coindesk.com/v1/bpi/historical/close.json?currency=\(currency)").responseJSON{ (responseData) in
if responseData.result.value != nil {
let responseJSON = JSON(responseData.result.value)["bpi"].dictionaryObject
self.exchange.currencyPast30DaysDatesArray = Array(responseJSON!.keys)
self.exchange.currencyPast30DaysPriceArray = Array(responseJSON!.values) as! [Double]
performSegue(withIdentifier: "currencyHistorySegue", sender: self)
}
}

这会有帮助。

关于swift - 如何处理alamofire的异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48354323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com