'Inserting multiple new rows to UITableView fails after 3 times

I read Apple's documentation and many other people's questions in here but still can't fully understand the structure of how to insert multiple rows to the UITableView using the insertRows(at:with:).

Can someone please explain in simple English how to do so?

I am using an API to fetch articles. I use pagination. Every time I fetch a new "batch" of articles I want to add them at the bottom of the UITableView.

When I run my code - it works 3 times and then I get an error and I can't figure out why -.-

This is my function and my attempt of adding the rows:

func fetchNewsFromAPI(searchWords: String = "news", pageSizeToFetch: PageSizeForFetching, completionHandler: @escaping (String?, Int?) -> ()) {
    repository.fetchNewsFromAPI(searchWords: searchWords, pageSizeType: pageSizeToFetch, savedArticles: savedArticles, currentPage: currentPaginationPage) {
        articles, totalPages, statusMsg in
        if let statusMsg = statusMsg {
            self.newsArray = []
            completionHandler(statusMsg, nil)
        } else {
            print("TOTAL RESULTS: \(totalPages!)")
            self.currentPaginationPage += 1
            if let totalPages = totalPages {
                self.totalPaginationPages = totalPages
            }
            self.newsArray.append(contentsOf: articles!)
            completionHandler(nil, articles?.count)
        }
    }
}



        func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let position = scrollView.contentOffset.y
    if position > (searchResultsTableView.contentSize.height - 100 - scrollView.frame.size.height) && !isPaginating {
        isPaginating = true
        viewModel.fetchNewsFromAPI(searchWords: searchTextField.text!, pageSizeToFetch: .articlesList) { error, numArticlesFetched in
            if error == nil {
                DispatchQueue.main.async {
                    self.searchResultsDataSource.models = self.viewModel.newsArray
                    
                    print("JUST FETCHED \(numArticlesFetched!) ARTICLES")
                    if numArticlesFetched != 0 {
                        self.searchResultsTableView.beginUpdates()
                        var indexPaths = [IndexPath]()
                        let rangeStart = numArticlesFetched!
                         let rangeEnd = rangeStart + (numArticlesFetched! - 1)
                         for i in rangeStart...rangeEnd {
                             indexPaths.append(IndexPath(row: i, section: 0))
                         }
                        self.searchResultsTableView.insertRows(at: indexPaths, with: UITableView.RowAnimation.right)
                        self.searchResultsTableView.endUpdates()
                    }
                    
                    self.searchResultsTableView.tableFooterView = nil
                }
            } else {
                print(error!)
            }
            self.isPaginating = false
        }
    }
}

But I get the following error:

Thread 1: "attempt to insert row 7 into section 0, but there are only 7 rows in section 0 after the update"


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source