Reputation: 99
I have Problem in my CollectionView:
here is the 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()
}
I have a array with device Ids:
let devArray = defaults.mutableArrayValue(forKey: "savedDevs")
So let's pretend there are 4 Ids in the devArray.
My numberOfItemsInSection looks like this:
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filteredArray.count
}
Here I have to use filteredArray.count, because when I start the App this happens:
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
The Problem is, that after the NSLOG "Start Task" the CollectionView functions for numberOfSections and numberOfItemsInSection are called.
at this time, the URL session is not completed and the cellForItemAt crashes with "Index out of range"
What have I done wrong here?
Upvotes: 1
Views: 155
Reputation: 3657
Make your array self.Devs = []
empty in viewWillAppear()
after getting the response assign it self.Devs = jsonData["devices"] as! [[String:AnyObject]]
and call reloadData()
method.
Upvotes: 1