Reputation: 417
My code:
DataService.dataService.fetchDataFromServer { (channel) in
self.channels.append(channel)
let indexPath = IndexPath(item: self.channels.count - 1, section: 0)
self.collectionView?.insertItems(at: [indexPath])
}
Fetch Data From Server Function:
func fetchDataFromServer(callBack: @escaping (Channel) -> ()) {
DataService.dataService.CHANNEL_REF.observe(.childAdded, with: { (snapshot) in
let channel = Channel(key: snapshot.key, snapshot: snapshot.value as! Dictionary<String, AnyObject>)
callBack(channel)
})
}
Number of Items Section:
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return 0
}
The Full Error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert item 0 into section 0, but there are only 0 items in section 0 after the update'
I am working with a collection view and have no clue why this error is showing up.
Any help would be appreciated!
Upvotes: 1
Views: 10523
Reputation: 895
For other users stumbling upon this question, these errors also arise when trying to update a TableView or CollectionView with no dataSource
assigned. Make sure the TableView's dataSource
is connected (when using a storyboard or nib) or assigned programmatically.
Upvotes: 2
Reputation: 15
Make sure you connected the datasource, that was something that tripped me up because its so basic and sometime you don't think about it.
Upvotes: 1
Reputation: 1377
I was having the same problem and fixed putting [unowned self] in the closure and forcing UI updates to be done on main thread. Also, as the others have said, the numberOfItemsInSection method should return the number of items in your array. Here is my final code:
DataManager.fetchDish() { [unowned self] dish in
if let dish = dish {
DispatchQueue.main.async {
self.dishes.append(dish)
self.dishesCollectionView.insertItems(at: [IndexPath(row: self.dishes.count - 1, section: 0)])
}
}
}
Upvotes: 4
Reputation: 114975
Your numberOfItemsInSection
is returning 0, so when tell the collection view you are adding an item, it gets upset when this method says that there are still 0 items in the collection.
Your code even has a comment // #warning Incomplete implementation, return the number of items
You probably want something like:
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.channels.count
}
Upvotes: 5