Load partial data for tableview on scroll down

Hi,


I am fetching data for my table view via a web service. Based on the request the result set can vary between 1 row and 20,000 rows. I know that usually my users are just interested in the first 1,000 rows of the data so I am wondering to have an approach where the initial web service call just loads the top 1,000 rows and when the user scrollls down the list and gets to the 800s, 900s or end of table, another request is triggered to fetch the next 1,000 rows - kinda similar to a Twitter feed where the data gets loaded once you scrolld down.


What would the events be to trigger the call for the next set of data or is there another way to make this happen?


Max

Answered by Claude31 in 409147022

I would try to implement this in


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell


This is called a a cell needs to be loaded.

So, I would keep an index of the last loaded item (1000 at first)

var lastLoaded = 0

Set its value when you send the web request

in cellForRowAt, test if index.row >= lastLoaded - 100

Then initiate a new web request for the next 1000 (do it in another thread to avoid blocking the scroll)

but update immediately lastLoaded += 1000

Accepted Answer

I would try to implement this in


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell


This is called a a cell needs to be loaded.

So, I would keep an index of the last loaded item (1000 at first)

var lastLoaded = 0

Set its value when you send the web request

in cellForRowAt, test if index.row >= lastLoaded - 100

Then initiate a new web request for the next 1000 (do it in another thread to avoid blocking the scroll)

but update immediately lastLoaded += 1000

Thanks! And how would I manage that in SwiftUI with a List element?

Should try a similar approach. Creating a @State var to replace lastLoaded.


Anyway, you should close this thread on the correct answer (if answer is OK) and start a new thread in SwiftUI (possibly refering to this one). You'll find people more focused to answer your question.

What you want to do is "prefetch" the data. See UITableViewDataSourcePrefetching for more information.

Thanks John! Now I just need something that also works with SwiftUI 🙂

see https://forums.developer.apple.com/thread/129897

Load partial data for tableview on scroll down
 
 
Q