Search code examples
iosweb-servicesuitableviewfeed

Is it advisable to call Web Services on cellForRowAtIndexPath for large datasets?


If the data set is too large and I want to show the data on a table View. What should be the best possible approach ?

First Approach- I call the API in cellForRowAtIndexPath. This would make the request everytime I scroll which would mean hitting the service again and again. May be I can cache the data as well but still I think it is not the best possible approach.

Second Approach- First, Save all the data locally and then show it. This would mean occupying more of the internal storage.

Which approach is better or is there any better approach available ?


Solution

  • What approach will you take depends on whether your API supports pagination or not! If the API does not support pagination then you left with no other solution then to retrieve every thing in one shot and show it in tableView.

    If your API supports pagination, then you can make a call to load the first page in ViewDidLoad and then implement scrollViewDidScroll delegate to check when user scrolled to Bottom of the table/collectionView and trigger the web service to fetch next page of response. This will continue till server responds with empty array.

    Here is a simple scrollViewDidScroll override which you can make use of to decide if user reached end of tableView/collectionView

    extension ViewController : UIScrollViewDelegate {
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            let bottomEdge = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.bounds.height
            if scrollView.contentOffset.y >= bottomEdge {
                //make a webservice call now
            }
        }
    }