gpt4 book ai didi

json - Swift 4 将数据从 json 保存到数组以在 TableView 中显示

转载 作者:可可西里 更新时间:2023-11-01 00:20:45 26 4
gpt4 key购买 nike

我正在尝试将数据从 func getCoinData 保存到数组 sympolsCoin 和数组 sympolsCoin 以在我的 TableView 中使用它

我在同一个 ViewController.swift 文件中创建了这个类:

struct Coin: Decodable {

let symbol : String
let price_usd : String }

这在我的 View Controller 类中:

var coins = [Coin]()


var sympolsCoin = [String]()
var priceUSDcoin = [String]()



func getCoinData(completion: @escaping () -> ()) {
let jsonURL = "https://api.coinmarketcap.com/v1/ticker/"
let url = URL(string: jsonURL)

URLSession.shared.dataTask(with: url!) { (data, response, error) in

do {
self.coins = try JSONDecoder().decode([Coin].self, from: data!)

for info in self.coins {

self.sympolsCoin.append(info.symbol)
self.priceUSDcoin.append(info.price_usd)

print("\(self.sympolsCoin) : \(self.priceUSDcoin)")

completion()
}

}


catch {
print("Error is : \n\(error)")
}
}.resume()
}

当我在 TableView 中使用数组时,我得到了空白表格!

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "BitcoinTableViewCell", for: indexPath) as! BitcoinTableViewCell

cell.coinNameLable.text = sympolsCoin[indexPath.row]
cell.priceLable.text = priceUSDcoin[indexPath.row]

return cell

}

最佳答案

由于您使用的是 JSONDecoder,因此创建和填充 sympolsCoinpriceUSDcoin 的整个逻辑毫无意义且多余。

struct Coin: Decodable {
private enum CodingKeys: String, CodingKey {
case symbol, priceUSD = "price_usd"
}
let symbol : String
let priceUSD : String
}

var coins = [Coin]()

完成处理程序也是多余的。接收到数据后,只需在主线程上重新加载 TableView 即可:

func getCoinData() {
let jsonURL = "https://api.coinmarketcap.com/v1/ticker/"
let url = URL(string: jsonURL)

URLSession.shared.dataTask(with: url!) { [unowned self] (data, response, error) in
guard let data = data else { return }
do {
self.coins = try JSONDecoder().decode([Coin].self, from: data)
DispatchQueue.main.async {
self.tableView.reloadData()
}

} catch {
print("Error is : \n\(error)")
}
}.resume()
}

viewDidLoad中加载数据

override func viewDidLoad() {
super.viewDidLoad()
getCoinData()
}

cellForRow 中更新 UI

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "BitcoinTableViewCell", for: indexPath) as! BitcoinTableViewCell

let coin = coins[indexPath.row]
cell.coinNameLable.text = coin.symbol
cell.priceLable.text = coin.priceUSD

return cell

}

关于json - Swift 4 将数据从 json 保存到数组以在 TableView 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48033007/

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