使用Swift 4加载数据时出现JSON catch错误

时间:2018-01-15 22:36:46

标签: ios json swift uitableview swift4

我的应用程序在过去3周内完美运行,然后今天我在构建应用程序时遇到了错误

Api:https://api.coinmarketcap.com/v1/ticker/

这是我的代码

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

struct Coin: Codable {
   let symbol : String
   let price_usd : String
   let percent_change_24h : String }

这在我的View控制器类中:

var coins = [Coin]()

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




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


    if reachability.connection == .none {
        print("No Internet")

        let noConnection = UIAlertController(title: "Error!", message: "Could not load data, Please check your internet connection and try again.", preferredStyle: .alert)
        let dismiss = UIAlertAction(title: "OK", style: .default, handler: nil)

        noConnection.addAction(dismiss)
        present(noConnection, animated: true, completion: nil)

    }else{

    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)
                self.lastDayChange.append(info.percent_change_24h)

                DispatchQueue.main.async {
                    self.coinTableView.reloadData()
                }
                //self.coinTableView.reloadData()
                print("JSON DATA HERE : \(self.sympolsCoin)")

            }

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

这是我的桌面视图:

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

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

    let lineNumbers = Array(1...200)

    let priceFormatter = NumberFormatter()
    priceFormatter.maximumFractionDigits = 4
    priceFormatter.minimumIntegerDigits = 1
    priceFormatter.numberStyle = NumberFormatter.Style.decimal

    let priceUSD = priceUSDcoin.flatMap{ priceString->String? in
        guard let price = Double(priceString) else {return nil}
        return priceFormatter.string(for: price)
    }

    cell.lineNumberLable.text =  " \(lineNumbers[indexPath.row]) -"
    cell.coinNameLable.text = " \(sympolsCoin[indexPath.row])"
    cell.priceLable.text = "$" + priceUSD[indexPath.row]
    cell.lastDayChange.text = lastDayChange[indexPath.row] + "%"

    return cell

}

错误来自catch并将此错误打印到consol:

错误是: valueNotFound(Swift.String,Swift.DecodingError.Context(codingPath:[Foundation。(_ JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue:“Index 22”,intValue:Optional(22)),Bitcoin_tracker.Coin。(CodingKeys in _498D704279C37C1773C9142E11B45D14).percent_change_24h] ,debugDescription:“预期字符串值,但发现为null。”,underlyingError:nil))

请帮助我,我是swift和JSON的新手

0 个答案:

没有答案