【发布时间】:2018-09-18 18:04:26
【问题描述】:
我正在尝试从网络请求中获取 collectionViewCell 计数,但结果始终为 0(我将 count 变量初始化为该值)我希望视图在从 get 请求中获取计数后加载单元格.我做错了什么我在super.viewDidLoad()之后写了这段代码。
DispatchQueue.global(qos:.background).async {
let token = "---------------------------"
let url = URL(string: "https:----------home.json?token="+token)!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
// print(String(data: data, encoding: .utf8)!)
let jsonWithObjectRoot = try? JSONSerialization.jsonObject(with: data, options: [])
// print(json!)
if let dictionary = jsonWithObjectRoot as? [String: Any] {
if let data = dictionary["data"] as? [String:Any]{
if let posts = data["posts"] as? [Any]{
count = posts.count
//print(count) //the value here is 2
for object in posts{
if let contentString = object as? [String: Any] {
print(contentString["title"] as! String)
// print(contentString["entered"]as! String)
}
}
}
}
}
}
task.resume()
/* end Request */
DispatchQueue.main.async{
self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout()
}
}
【问题讨论】:
-
task.resume()异步运行,因此reloadData在您的数据加载之前被触发。
标签: ios swift asynchronous