'Preloading data from network in UITableView

I have a page that support pagination when loading data from network.

I'm using a UITableview to display list.

I want to preload next page when user scroll near the end of current page.

For example, each page has 10 items. When item 8 is visible in the screen, I shall start loading of next page immediately.

Which delegate method of UITableView is the best choice for this task?



Solution 1:[1]

UITableView is a subclass of UIScrollView, so you can use it delegate methods. I suggest you to use this two:

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {

    if (!decelerate) {
         NSSet *visibleRows = [NSSet setWithArray:[self.view.tableView indexPathsForVisibleRows]];

    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    NSSet *visibleRows = [NSSet setWithArray:[self.view.tableView indexPathsForVisibleRows]];

}

Check your clause after you get visibleRows and preload your data if, for example, last indexPath.row in NSSet is equal to your datasource array count (or is equal to [array count] - some_number_you_want )

To archive, when tableView start scrolling, you can implement your preload logic here:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {

    NSSet *visibleRows = [NSSet setWithArray:[self.view.tableView indexPathsForVisibleRows]];
// your update code here
}

Hope this helps.

Solution 2:[2]

add this method in the UITableViewDelegate:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{   
    CGFloat height = scrollView.frame.size.height;

    CGFloat yOffset = scrollView.contentOffset.y;

    CGFloat distanceFromBottom = scrollView.contentSize.height - yOffset;

    if(distanceFromBottom < height) 
    {
        NSLog(@"end of the table and call web service or load more data");
    }
}

Solution 3:[3]

Use UITableViewDataSourcePrefetching or UICollectionViewDataSourcePrefetching to preload data from network and have your cells ready when displayed to the user

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Doro
Solution 2 Mahesh
Solution 3 Radu Ursache