Preloading data from network in UITableView

810 views Asked by At

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?

4

There are 4 answers

0
Myaaoonn On BEST ANSWER

Try the following method, It will get to know the display cell

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath
    {
//      Webservice Call for next 10 display data
    }

Discussion A table view sends this message to its delegate just before it uses cell to draw a row, thereby permitting the delegate to customize the cell object before it is displayed. This method gives the delegate a chance to override state-based properties set earlier by the table view

1
Doro On

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.

1
Mahesh On

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");
    }
}
0
Radu Ursache On

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