Reputation: 37
I have an API that takes a parameter called "take"
. In viewDidLoad, I am passing 10 and I got 10 data and append them into my array of objects. I use scrollViewDidEndDragging
method for pagination like below. I increase my takeCount by ten by and called my API again and append them to my existing array. Problem is that the 1
. object and 11
. The object is the same when I scroll to the bottom. Should I remove old data but isn't it against the logic of pagination?
Pagination Code
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView.contentOffset.y > scrollView.contentSize.height - scrollView.frame.size.height{
self.takeCount += 10
if self.takeCount <= self.sampleDataCountLimit{
Service().fetchData(count: self.takeCount) { (result) in
switch result{
case .success(let cars):
//self.carModel.removeAll(keepingCapacity: false)
self.carModel.append(contentsOf: cars)
DispatchQueue.main.async {
self.tableView.reloadData()
print(self.carModel.count)
print(self.carModel)
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
}
Upvotes: 2
Views: 723
Reputation: 2859
When you call your API with the take=20
parameter, it just returns first 20 items, and those 20 items also include the same items that the API would return with take=10
. So when you append the new result to the previous result, you get duplicated items because your previous result already contained some of the items from the new result. It means that you need to replace the old data with the new data each time you call your API to avoid item duplication.
Pagination usually doesn't work like that. The API should typically accept either a range (something like start=10&end=20
) or the page number (optionally with the page size, for example pagesize=10&pagenumber=2
).
You should check if your API supports something like that.
Alternatively, if the number of returned items will never be huge, you can opt out from using pagination completely and fetch all items in one request.
If the number of items can be huge, but your API can only return first N items, you might keep the logic when you first fetch first N items, then 2N items, then 3N and so on and completely replace the data each time, but that is far from ideal.
Upvotes: 2