代码之家  ›  专栏  ›  技术社区  ›  Rashed

使用SwiftyJSON和Alamofire在TableView上创建JSON数据

  •  0
  • Rashed  · 技术社区  · 7 年前

    我想在表视图上显示数据。问题是,我不能让它出现在上面。我的代码如下所示,我希望有人能帮助我。

    import Foundation
    
    struct HeroStats {
    
      let localized_name: String
      let primary_attr: String
      let attack_type: String
      let legs: String
      let img: String
    }
    

    以下是我的viewController代码:

    import UIKit
    import Alamofire
    import SwiftyJSON
    
    class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
      @IBOutlet var tableView: UITableView!
      var heros = [HeroStats]()
    
      override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
        downloadJson()
        self.tableView.reloadData()
    
    
        tableView.delegate = self
        tableView.dataSource = self
    
      }
    
      func tableView(_ tableView: UITableView, numberOfRowsInSection 
    section: Int) -> Int {
        return heros.count
      }
    
      func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
    IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
        cell.textLabel?.text = 
        heros[indexPath.row].localized_name.capitalized
        return cell
      }
    
      //MARK: Parsing JSON data
      func downloadJson(){
    Alamofire.request("https://api.opendota.com/api/heroStats").responseJSON { response in
    
            if let value = response.result.value {
    
               let json = JSON(value)
    
            //Printing strings from a JSON Dictionary
            print(json[0]["localized_name"].stringValue)
            print(json[0]["primary_attr"].stringValue)
            print(json[0]["attack_type"].stringValue)
            print(json[0]["legs"].stringValue)
            print(json[0]["img"].stringValue)
           }
        } // End Alamofire call
      }
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Francis.Beauchamp    7 年前

    请求是 async . 当它给您一个结果时,您需要对其进行解析并将其分配给 HeroStat . 这需要在请求完成处理程序中完成。您当前正在执行 没有什么 在你得到回应之后。此外,您对重新加载数据的调用是在您实际收到响应之前完成的,所以这不起作用。

    您可以做的是:一旦得到响应,就填充 heros 数组和调用 tableView.reloadData() 使其获取新填充的 HeroStat公司 价值观