我的CollectionView中有问题:
这里是viewWillAppear:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let urlSession = URLSession(configuration: config)
NSLog("Start URLSession")
NSLog("Start Task")
let task = urlSession.dataTask(with: url) { (data, response, error) in
NSLog("task started")
guard let data = data, error == nil else {
print("error: \(String(describing: error))")
//self.collectionView?.addSubview(blurView)
//customActivityIndicatory(self.view)
let alert = UIAlertController(title: "Error", message: "Connection Error", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "OK", style: .default) { action in
// perhaps use action.title here
})
OperationQueue.main.addOperation {
self.present(alert, animated: false)
}
return
}
do {
guard let jsonData = try? JSONSerialization.jsonObject(with: data, options: []) as! [String:Any] else {
print("jsonError")
return
}
//adressiere Array in JSON Dictionary
self.Devs = jsonData["devices"] as! [[String:AnyObject]]
NSLog("Json parsed")
//Filter Array
self.filteredArray = self.Devs.filter { self.devArray.contains($0["id"] as! String) }
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
}
}
task.resume()
}
我有一个带有设备ID的数组:
let devArray = defaults.mutableArrayValue(forKey: "savedDevs")
因此,让我们假装devArray中有4个ID。
我的numberOfItemsInSection看起来像这样:
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filteredArray.count
}
这里我必须使用filteredArray.count,因为当我启动App时会发生这种情况:
2017-09-05 16:21:51.411 [62695:2391013] notfirstStart
2017-09-05 16:21:51.437 [62695:2391013] Start URLSession
2017-09-05 16:21:51.453 [62695:2391013] Start Task
sections:
numberOfItemsInSection: 0
2017-09-05 16:21:52.450 [62695:2391109] task started
2017-09-05 16:21:52.462 [62695:2391109] Json parsed
sections:
numberOfItemsInSection: 4
问题是,在NSLOG"开始任务后#34;调用numberOfSections和numberOfItemsInSection的CollectionView函数。
此时,URL会话未完成且cellForItemAt崩溃,"索引超出范围"
我在这里做错了什么?
答案 0 :(得分:1)
在获得响应后,在self.Devs = []
中将您的数组viewWillAppear()
清空self.Devs = jsonData["devices"] as! [[String:AnyObject]]
并调用reloadData()
方法。