swift tableview insertRows

Работаю с firebase, показываю посты, сделал, чтоб при прокрутке tableview ближе к концу загружались новые посты, что бы не было эффекта лага сделал добавление новых постов через insertRows вместо reloadData, но проблема в том, что, если быстро прокрутить вниз, то крашится с ошибкой :

invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (19) must be equal to the number of rows contained in that section before the update (10)

если скроллить медленно, то ошибки не возникает, помогите разобраться почему так происходит и как это исправить

var fetchingMore = false
var endReached = false
let leadingScreensForBatching:CGFloat = 3.0

func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch section {
    case 0:
        return tasks.count
    case 1:
        return 1 //fetchingMore ? 1 : 0
    default:
        return 0
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "loadingCell", for: indexPath) as! LoadingTableViewCell
        cell.spinner.startAnimating()
       
        return cell
    }
    ...
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offsetY = scrollView.contentOffset.y
    let contentHeight = scrollView.contentSize.height
    if offsetY > contentHeight - scrollView.frame.size.height * leadingScreensForBatching {
        if !fetchingMore && !endReached {
              beginBatchFetch(insert: true)
             
        }
    }
}

func beginBatchFetch(insert:Bool = false) {
    if !fetchingMore {
        fetchingMore = true
        self.tableView.reloadSections(IndexSet(integer: 1), with: .fade)
        DataService.dataService.getTasks(by: type, lastValue: lastValue, lastKey: lastKey) { (_tasks) in
        if !isInsert {
            self.tasks.removeAll()
        }
        self.tasks.append(contentsOf: _tasks)
        
        if isInsert {
            let indexPaths = (self.tasks.count - _tasks.count ..< self.tasks.count)
                .map { IndexPath(row: $0, section: 0) }
            DispatchQueue.main.async {
                self.tableView.beginUpdates()
                self.tableView.insertRows(at: indexPaths, with: .automatic)
                self.tableView.endUpdates()
            }
        }else{
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
        
        self.fetchingMore = false
        self.endReached = _tasks.count == 0
        
    }
}

Данные беру с firebase по 10 постов за раз. Я не совсем понимаю, почему при быстром скролле (просто резко дергаю скролл) - вылетает с ошибкой, в деббагере смотрел - данные получаю такие же, как и при медленном скролле, помогите разобраться


Ответы (0 шт):