【问题标题】:Swift 4 saving data from json to an array to show it in TableViewSwift 4 将数据从 json 保存到数组以在 TableView 中显示
【发布时间】:2018-06-10 12:12:24
【问题描述】:

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

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

struct Coin: Decodable {

let symbol : String
let price_usd : String } 

这在我的视图控制器类中:

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

}

【问题讨论】:

    标签: json swift uitableview tableview swift4


    【解决方案1】:

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

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

    var coins = [Coin]()
    

    完成处理程序也是多余的。接收到数据后在主线程上重新加载表格视图即可:

    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 更新用户界面

    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
    
    }
    

    【讨论】:

      【解决方案2】:

      您需要从主线程更新 tableView。作为一个很好的教训:始终从主线程更新 UI。总是。

      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) 
      
                  DispatchQueue.main.async {
                      self.tableView.reloadData()
                  }
      
                  print("\(self.sympolsCoin) : \(self.priceUSDcoin)")
      
                  completion()
              }
      
          }
      

      但是,您的代码存在另一个问题,即您设置标签的方式不起作用。 TableViewCells 得到重用,所以我猜你在其他地方有@IBOutlets。你应该做的是在 cellForRowAt 中声明一个标签常量:

      override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
      
          let coinNameLabel = cell.viewWithTag(100) as! UILabel
          coinNameLabel.text = sympolsCoin[indexPath.row]
          let priceNameLabel = cell.viewWithTag(101) as! UILabel
          priceNameLabel.text = priceUSDcoin[indexPath.row]
      }
      

      上面的代码假设您在故事板中设置了两个标签,标签为 100 和 101(假设您使用一个)

      【讨论】:

        【解决方案3】:

        在 ViewController 类中创建一个 tableView 的 Outlet 并命名为“tableView”然后 试试这个代码:Swift 4

        func getCoinData() {
            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)")
        
                        self.tableView.reloadData()
                    }
        
                }
        
                catch {
                    print("Error is : \n\(error)")
                }
          }.resume()
        }
        

        像这样在ViewDidLoad中调用这个函数

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

        【讨论】:

        • 我有一个小问题..当应用程序加载任何内容以显示在表格视图中,直到我向下或向上滚动然后数据显示!
        • 转到您的 getCoinData(),将“self.tableView.reloadData()”替换为 DispatchQueue.main.async { self.tableView.reloadData() }
        【解决方案4】:

        **

        // First View Controller
        //
        //
        //
        import UIKit
        struct Countory : Decodable {
            let name: String
            let capital: String
            let region: String
            let alpha2Code: String
        }
        class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
          var listArr = [Countory]()
            @IBOutlet weak var tableView: UITableView! 
            override func viewDidLoad() {
                super.viewDidLoad()
                self.tableView.delegate = self
                self.tableView.dataSource = self
                let url = "https://restcountries.eu/rest/v2/all"
                let urlObj = URL(string: url)!
                URLSession.shared.dataTask(with: urlObj) {(data, responds, Error) in
                 do {
                  self.listArr = try JSONDecoder().decode([Countory].self, from: data!)
                     for country in self.listArr {
        
                            print("Country",country.name)
                            print("###################")
                            print("Capital",country.capital)
                         DispatchQueue.main.async {
                               self.tableView.reloadData()
                            }
                        }
                    } catch {
                        print(" not ")
                    }
                }.resume()
            }
             func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                return self.listArr.count
            }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
                cell.label1.text = "Name: \(listArr[indexPath.row].name)"
                cell.lable2.text = listArr[indexPath.row].capital
                return cell
            }
        
            func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                let homeView = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
                  homeView.res = listArr[indexPath.row].region
                  homeView.alpha = listArr[indexPath.row].alpha2Code
               self.navigationController?.pushViewController(homeView, animated: true)
        
            }
        
            func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
                return 100
            }
        }
        // SecondViewController
        class SecondViewController: UIViewController {
            @IBOutlet weak var label4: UILabel!
            @IBOutlet weak var label3: UILabel!
        
            var res = ""
            var alpha = ""
        
            override func viewDidLoad() {
                super.viewDidLoad()
        
                self.label3.text = res
                self.label4.text = alpha
        
            }
        
        }
        

        **

        【讨论】:

          猜你喜欢
          • 2020-11-11
          • 1970-01-01
          • 1970-01-01
          • 2015-08-17
          • 1970-01-01
          • 1970-01-01
          • 2018-09-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多