我无法更新retRecalls数组。它在循环中更新但主要是空的,我无法找出原因。如果我在viewDidLoad中打印为空,如果我在循环中打印就可以了。
var retRecalls = [Recalls]() ***** MAIN ARRAY
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
print(retRecalls) ***** EMPTY
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Alamofire.request(recallsApi+vehicle).responseJSON { response in
let result = response
if let returnDict = result.value as? [String:Any] {
if let recall = returnDict["recalls"] as? [[String:Any]] {
for i in recall {
let id = i["nnaId"]
let header = i["secondaryDescription"]
let summary = i["primaryDescription"]
let risk = i["riskIfNotRepaired"]
let remedy = i["remedyDescription"]
let recallsArray = Recalls(recallId: id as! String, header: header as! String, summary: summary as! String, risk: risk as! String , remedy: remedy as! String)
self.retRecalls.append(recallsArray)
print(retRecalls) **** IT'S UPDATING
}
}
}
}
tableView.reloadData()
}
}
谢谢
答案 0 :(得分:0)
因此,您需要等待网络调用在填充数组之前返回。
将reloadData()
置于网络操作之外意味着它会立即被调用。您希望在网络操作完成后将其推迟到已调用,并且已填充阵列。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Alamofire.request(recallsApi+vehicle).responseJSON { response in
let result = response
if let returnDict = result.value as? [String:Any] {
if let recall = returnDict["recalls"] as? [[String:Any]] {
for i in recall {
let id = i["nnaId"]
let header = i["secondaryDescription"]
let summary = i["primaryDescription"]
let risk = i["riskIfNotRepaired"]
let remedy = i["remedyDescription"]
let recallsArray = Recalls(recallId: id as! String, header: header as! String, summary: summary as! String, risk: risk as! String , remedy: remedy as! String)
self.retRecalls.append(recallsArray)
print(retRecalls) **** IT'S UPDATING
}
}
}
// Move the reloadData() call to here.
dispatchQueue.main.async {
tableView.reloadData()
}
}
// tableView.reloadData()
}
}