[英]Creating JSON data using SwiftyJson for MultipartFormData request in Alamofire 4
[英]JSON data on TableView using SwiftyJSON and Alamofire
我想在表視圖上顯示數據。 問題是,我無法顯示它。 我的代碼如下所示,希望有人能幫助我。
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
}
}
該請求是async
。 當它給您結果時,您需要對其進行解析並將其分配給HeroStat
數組。 這需要在您的請求完成處理程序中完成。 得到回應后,您目前無所事事 。 另外,對reloadData的調用是在您實際獲得響應之前完成的,因此不會進行。
您可以做的是:獲得響應后,填充heros
數組並調用tableView.reloadData()
以使其獲取新的填充的HeroStat
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.