'NSRangeException': row (1) beyond bounds (1) for section (0) - uitableview

I have a chat Application in which messages are being fetched and updated in my tablview using NSFetchResultsController.
Here is my code:
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
{
self.tblViewChatLog.endUpdates()
scrollToBottom(animated: true)
if self.fetchedResultsController.fetchedObjects?.count == 0 {
}
else {
}
}
func scrollToBottom(animated: Bool)
{
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1)
{
let secCount = self.tblViewChatLog.numberOfSections
if secCount > 0
{
let sections = self.fetchedResultsController.sections
let secInfo = sections?.last
let rows = secInfo?.objects //secInfo?.numberOfObjects
if (rows?.count)! > 0
{
let indexPath = NSIndexPath(row: (rows?.count)!-1, section: secCount-1)
self.tblViewChatLog.scrollToRow(at: indexPath as IndexPath, at: .bottom, animated: animated)
self.view.updateConstraintsIfNeeded()
self.tblViewChatLog.updateConstraintsIfNeeded()
}
}
}
}
I'm getting following error while trying to update my table.
Terminating app due to uncaught exception 'NSRangeException', reason: '-[UITableView _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:]: row (1) beyond bounds (1) for section (0).'
*** First throw call stack:
(0x21f15b0b 0x216d2dff 0x21f15a51 0x2672a9c1 0x2672a45f 0x13e7b4 0x54e90 0x19adba7 0x19b78e9 0x19adb93 0x19c156d 0x19afb43 0x19b2157 0x21ed7755 0x21ed5c4f 0x21e241c9 0x21e23fbd 0x23440af9 0x2655c435 0xcc554 0x21ad0873)
libc++abi.dylib: terminating with uncaught exception of type NSException

The error tells you that your table does not have any row at index 1. It means that your table view consists of 1 row and maximum range of indexPath.row can be 0 (because row index of a UITableView starts from 0). Whenever you will call a row at index path beyond range of the table, it will throw an error.

Related

contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:usingPresentationValues:]: row (0) beyond bounds (0) for section (0

I'm getting following exception at run time randomly. How do I stop it happening?
Fatal Exception: NSRangeException
-[UITableView _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:usingPresentationValues:]: row (0) beyond bounds (0) for section (0)
Code:
self.table.reloadData()
let lastIndexPath = IndexPath(row: 0, section: 0)
self.table.scrollToRow(at: lastIndexPath, at: UITableView.ScrollPosition.top, animated: false)
self.table.isHidden = false

Scroll to bottom as new content comes in

So I have a UICollectionView that sort of houses a chat function in my app. As users send new messages they are brought in to the app via an observer pattern. However when new content comes in. It ends up below the keyboard and never adjust itself up. When I toggle the keyboard I have a function like this which seems to accomplish this goal. However, when I try similar code in my completion handler it fails and gives me this message.
'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: {length = 2, path = 0 - 9}'
*** First throw call stack:
fileprivate func tryObserveComments(){
print(eventKey)
commentHandle = ChatService.observeMessages(forChatKey: eventKey) { (ref, newComments) in
self.commentRer = ref
self.comments.append(newComments!)
self.adapter.performUpdates(animated: true)
let item = self.collectionView.numberOfItems(inSection: self.collectionView.numberOfSections - 1) - 1
let insertionIndexPath = IndexPath(item: item, section: self.collectionView.numberOfSections - 1)
self.collectionView.scrollToItem(at: insertionIndexPath, at: UICollectionViewScrollPosition.top, animated: true)
}
}
Also for some reason in the strange instance that it does work. Some of the keyboard is partially covering the cell
Try it using performBatchUpdates, i think it will work as you excepted
fileprivate func tryObserveComments(){
print(eventKey)
commentHandle = ChatService.observeMessages(forChatKey: eventKey) { (ref, newComments) in
self.commentRer = ref
self.comments.append(newComments!)
self.adapter.performUpdates(animated: true)
self.collectionView.performBatchUpdates({
let item = self.collectionView.numberOfItems(inSection: self.collectionView.numberOfSections - 1) - 1
let insertionIndexPath = IndexPath(item: item, section: self.collectionView.numberOfSections - 1)
}, completion: { (Bool) in
self.collectionView.scrollToItem(at: insertionIndexPath, at: UICollectionViewScrollPosition.top, animated: true)
})
}
}

Easy way to reset scroll view position [duplicate]

This question already has answers here:
How to scroll to a particluar index in collection view in swift
(8 answers)
Closed 5 years ago.
I have horizontal UICollectionView, and i want to reset it X position. I tried following:
let indexPath = IndexPath(row: 0, section: 1)
self.collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition(rawValue: 0), animated: false)
However it not work, i got an error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: <NSIndexPath: 0x61000002d040> {length = 2, path = 1 - 0}'
How to scroll collection view to start?
This will not work if there are no items
self.collectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition(rawValue: 0), animated: false)
Use (Objective C):
CGPoint topOffest = CGPointMake(0,-self.collectionView.contentInset.top);
[self.collectionView setContentOffset:topOffest animated:YES];
Use (Swift):
let topOffest:CGPoint = CGPoint(0,-self.collectionView.contentInset.top)
collectionView?.setContentOffset(topOffest, animated: true)
self.collectionView.scrollToItem(at: [0,5], at:.centeredHorizantally, animated: false)
0 represents the Section Number 0
5 represents Cell no 5

FirebaseUI table view crashes with 'Invalid update: invalid number of rows in section 0

I have 3 table views within a tab controller, all of them are getting populated like this:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.dataSource = self.notesTableView.bind(to: getQuery()) { tableView, indexPath, snap in
let cell = self.notesTableView.dequeueReusableCell(withIdentifier: "cellident", for: indexPath)
let customCell = cell as! TextCell
self.notesTableView.dataSource = self.dataSource
self.notesTableView.delegate = self
if let note = snap.childSnapshot(forPath: "note").value as! String? {
customCell.notesLabel.text = note
} else {
customCell.notesLabel.text = "Undefined"
}
return cell
}
}
When I am running the app on my phone and switch between the tabs, after some point I am always running into this exception:
'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.
Furthermore, the console shows this, but I am not sure how to interpret this:
*** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3600.7.47/UITableView.m:1737
My question is if someone has an idea what the cause of this exception in relation to FirebaseUI might be. My guess is that it has to do with populating the tables.
In the viewWillDisappear set the self.dataSource = nil.
So, that you don't update the dataSource improperly.
from this question
here
from my experience, the safest way is in the viewWillDisappear set self.dataSource.unbind()

reloadData() doesn't work with refreshControl

I have UICollectionView that manages a lot of cells. When I delete a cell, I would like the cell disappears with a refreshControl. But I don't understand why the reloadData does not act. If anyone can help me thank you in advance.
In my view didLoad :
self.collectionView!.alwaysBounceVertical = true
let refresher = UIRefreshControl()
refresher.tintColor = MyColor.Color
refresher.addTarget(self, action: #selector(PublicListController.refreshStream), forControlEvents: .ValueChanged)
refreshControl = refresher
collectionView!.addSubview(refreshControl!)
collectionView.dataSource = self
self.populateDataBest()
My simply function :
func refreshStream() {
collectionView?.reloadData()
refreshControl?.endRefreshing()
}
I complete my CollectionView with the method populateDataBest :
func populateDataBest() {
self.videosService.get(true, completionHandler: {
videosBest, error in
dispatch_async(dispatch_get_main_queue(), {
if error != nil {
if error!.code == -999 {
return
}
self.displayError(informations.LocalizedConnectionError)
return
}
self.bestClip = videosBest
for (indexBest, _) in (self.bestClip?.enumerate())! {
let videoBest:Clip = self.bestClip![indexBest]
self.pictureArrayVideo.addObject(["clip": videoBest, "group": "BEST"])
}
self.dataSource.updateData(self.pictureArrayVideo)
self.collectionView.reloadData()
})
})
}
And the first reload work at the end of my method populateDataBest..
EDIT :
I try to implement function who remove my element (I put 0 in parameters on remove method just for my test for the moment)
func refreshStream() {
dispatch_async(dispatch_get_main_queue(), {
self.remove(0)
self.collectionView.reloadData()
})
self.refreshControl.endRefreshing()
}
func remove(i: Int) {
self.listForPager.removeAtIndex(i)
let indexPath: NSIndexPath = NSIndexPath(forRow: i, inSection: 0)
self.collectionView.performBatchUpdates({
self.collectionView.deleteItemsAtIndexPaths(NSArray(object: indexPath) as! [NSIndexPath])
}, completion: {
(finished: Bool) in
self.collectionView.reloadItemsAtIndexPaths(self.collectionView.indexPathsForVisibleItems())
})
}
And I have this error after
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (8) must be equal to the number of items contained in that section before the update (8), plus or minus the number of items inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).'
Someone know why and can help me plz ?
Thx in advance.
If you are riding your collection from an array you should also delete the item for the line will disappear and finally to reload.

Resources