我想使用Alamofire获取用户数据并将其填充到tableView中。
我的代码:
class MainTableViewController: UITableViewController {
var userEntries = [UserEntries]()
override func viewDidLoad() {
super.viewDidLoad()
fetchUserData { (ue) in
print("ue.count is: \(ue.count)")
self.userEntries = ue
print("self.userEntries.count in this block: \(self.userEntries.count)")
}
print("self.userEntries.count in viewDidLoad is: \(self.userEntries.count)")
}
func fetchUserData(completion: @escaping ([UserEntries]) -> Void) {
//another code...
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .httpBody), headers: headers).responseJSON { (response) in
switch response.result {
case .success(let value):
let json = JSON(value)
let data = json["mydata"][0].array
var userEntries = [UserEntries]()
//I have 2 records only
data?.forEach({ (p) in
userEntries.append(UserEntries(id: p["id"].stringValue, date: p["date"].stringValue, text: p["text"].stringValue))
})
completion(userEntries)
case .failure(let error):
print(error.localizedDescription)
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.userEntries.count //it is return 0...
}
}
在viewDidLoad中,我有以下照片:
viewDidLoad中的self.userEntries.count是:0 //必须为2 !!!
ue.count是:2
self.userEntries.count在此块中:2
并且在numberOfRowsInSection方法中返回0,因为
viewDidLoad中的self.userEntries.count是:0 //必须为2 !!!
如何正确设置'self.userEntries'变量(数组)以在tableView方法中使用它?
答案 0 :(得分:1)
由于获取数据的调用是异步的,因此您需要在完成过程中重新加载表
fetchUserData { (ue) in
print("ue.count is: \(ue.count)")
self.userEntries = ue
print("self.userEntries.count in this block: \(self.userEntries.count)")
self.tableView.reloadData()
}