我正在调用我的webservice来返回JSON数据,然后将其用于填充UICollectionView中的单元格。为了确定单元格的数量,我计算JSON数组中返回的项目数。但是,问题是我的collectionView()函数在我的dataTask()函数完成之前被调用(我的猜测是dataTask()是异步的),这反过来给我一个错误,详细说明我访问了一个nil值(TestController.swift中的jsonCount变量)。我尝试过使用各种completionHandler和返回值,但我无法让它工作。你能帮我们指点一下正确的方向吗?
非常感谢您的帮助/意见。
HomeModel.swift
class func getPostings(completionHandler: @escaping (_: Any) -> ()) {
let url: URL = URL(string: "url")!
let request: URLRequest = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) {data,
response, error in
guard error == nil else {
print(error!)
completionHandler("Failed")
return
}
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if statusCode == 200 {
let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [[String: Any]]
completionHandler(json!)
}
}
task.resume()
TestController.swift
var jsonCount: Int?
var jsonData: [[String: Any]]?
override func viewDidLoad() {
super.viewDidLoad()
HomeModel.getPostings(completionHandler: {(response: Any) -> Void in
guard response as? String != "Failed" else {
//Code to send a pop-up alert to the user
return
}
self.jsonData = response as? [[String: Any]]
self.jsonCount = (self.jsonData?.count)!
})
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return jsonCount
}
答案 0 :(得分:1)
CollectionView
或TableView
默认情况下会在ViewDidLoad
方法上重新加载。但是当您从服务器下载某些内容时,只需在主线程上完成下载任务更新UI。
HomeModel.getPostings(completionHandler: {(response: Any) -> Void in
guard response as? String != "Failed" else {
//Code to send a pop-up alert to the user
return
}
self.jsonData = response as? [[String: Any]]
self.jsonCount = (self.jsonData?.count)!
DispatchQueue.main.async {
// Update UI on Main Thread
collectionView.reloadData()
}
})