[英]JSON data on TableView using SwiftyJSON and Alamofire
I want to show data on a Table View. 我想在表视图上显示数据。 The problem is, I can't get it to show up on it.
问题是,我无法显示它。 My code is shown below and I hope somebody can help me out.
我的代码如下所示,希望有人能帮助我。
import Foundation
struct HeroStats {
let localized_name: String
let primary_attr: String
let attack_type: String
let legs: String
let img: String
}
Here is my viewController code: 这是我的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
}
}
The request is async
. 该请求是
async
。 When it gives you a result, you need to parse it and assign it to your array of HeroStat
. 当它给您结果时,您需要对其进行解析并将其分配给
HeroStat
数组。 That needs to be done in your request completion handler. 这需要在您的请求完成处理程序中完成。 You are currently doing nothing after you get your response.
得到回应后,您目前无所事事 。 Also, your call to reloadData is done before you actually get a response, so that won't do.
另外,对reloadData的调用是在您实际获得响应之前完成的,因此不会进行。
What you could do is: Once you get your response, populate the heros
array and call tableView.reloadData()
to make it fetch the new populated HeroStat
values. 您可以做的是:获得响应后,填充
heros
数组并调用tableView.reloadData()
以使其获取新的填充的HeroStat
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.