Search code examples
iosswiftuitableviewuiscrollview

Falling into an infinite loop when trying to implement Infinite Scrolling using Swift


Assistance would be much appreciated with the following issue.

My code falls into an infinite loop when scrolling-up a tableView even though I have implemented the right boolean checks (so I believe)...

Bool to check if I am already fetching more content:

var fetchingMore = false

This is my scrollViewDidScroll func:

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    let offsetY = scrollView.contentOffset.y
    let contentHeight = scrollView.contentSize.height

    if offsetY > contentHeight - scrollView.frame.height{

        if !fetchingMore{

            radius += 5
            fetchMoreVenues()

        }//end if

    }//end if

}//end func

This is my fetchMoreVenues func which fetches more content but is being called infinitely for some reason:

func fetchMoreVenues(){

    fetchingMore = true

    DataService.run.fetchVenueNearby(deviceLocation: currentLocation, radius: radius) { (venues) in

        for venue in venues {

            if !self.venueArray.contains(where: { ($0.venueID == venue.venueID) }){
                self.venueArray.append(venue)
            }

            if !self.filteredVenueArray.contains(where: { ($0.venueID == venue.venueID) }){
                self.filteredVenueArray.append(venue)
            }

        }//end for

        self.fetchingMore = false
        self.tableView.reloadData() 

    }//end fetchVenueNearby

}//end func

Solution

  • May be reverse order

    self.tableView.reloadData() 
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
      self.fetchingMore = false
    }