场景:从上一个tableView点击传入uid,然后在viewDidLoad里面做数据查询,最后展示到tableView中。
问题:用Alamofire做GET请求得到结果,但在Alamofire打印结果条数为0,在Alamofire内打印有结果条数。具体请看代码
class SealViewController: UITableViewController {
var userId: String!
var seals: [SealModel] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print("uid->", userId)
//加在API JSON数据
Alamofire.request(.GET, SERVICEAPIDOMAIN + "/Mobile/MobileHandler.ashx?method=toAudit&uid=" + userId).responseJSON {
response in
if let apiData = response.result.value {
let json = JSON(apiData)
for var i = 0; i < json["items"].count; i++ {
let line = json["items"][i]
self.seals.append(SealModel(id: line["ID"].stringValue, title: line["TitleStr"].stringValue, content: line["ContentStr"].stringValue, dateTime: line["TimeStr"].stringValue, type: line["Type"].stringValue))
}
}
print("Alamofire-sealsCount->", self.seals.count)
}
tableView.reloadData()
print("sealsCount->", self.seals.count)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
输出结果
uid-> 69
sealsCount-> 0
Alamofire-sealsCount-> 12
viewDidLoad 是 View 加载完成之后执行的函数,网络请求是异步行为,你在请求完成之后才能获取得数据,但此时 viewDiDLoad 已经执行完毕了,需要展示到 tableView ,可以在获取网络请求的响应之后再 reloadData