【问题标题】:JSON data on TableView using SwiftyJSON and AlamofireTableView 上使用 SwiftyJSON 和 Alamofire 的 JSON 数据
【发布时间】:2018-01-05 17:58:30
【问题描述】:

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

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
  }
}

【问题讨论】:

  • 看来heros 从未被赋予任何值。

标签: ios swift uitableview swifty-json


【解决方案1】:

请求是async。当它为您提供结果时,您需要对其进行解析并将其分配给您的HeroStat 数组。这需要在您的请求完成处理程序中完成。收到回复后,您目前什么都不做。此外,您对 reloadData 的调用是在您实际得到响应之前完成的,因此不会这样做。

您可以做的是:收到回复后,填充heros 数组并调用tableView.reloadData() 以使其获取新填充的HeroStat 值。

【讨论】:

    猜你喜欢
    • 2016-07-01
    • 1970-01-01
    • 2018-11-12
    • 2014-12-27
    • 1970-01-01
    • 2020-08-28
    • 2019-10-22
    • 1970-01-01
    • 2017-10-15
    相关资源
    最近更新 更多