cojoj
cojoj

Reputation: 6475

Downloading images only for visible UITableViewCells

In UITableViewController I have custom cells with thumbnail image which is cached by me using TMCache. So the basic workflow of loading cells is:

  1. Fill cell lables with data from model
  2. Check if I have a thumbnail image cached
  3. If yes, than get it from cache...
  4. If not, download it from web...

And me concerns are that when I don't have anything in cache I'd start downloading a lot of images (even if I have set maximum number of concurrent tasks) so when the user scrolls for example a 100 rows my tasks array in AFHTTPSessionManager will be dealing with all of then even if user is not interested in many of them.

So I came with this solution: When usere scrolls down and downloading begins, but in a moment this cell gets off the screen, I want to cancel NSURLSessionDataTaskfor this cell. But... I don't know how to check which cell should cancel its task and the more important issue, what if task is completed in 90% and I cancel it (waste of data transfer)? I've noticed that in Facebook app they're not cancelling those tasks because when you scroll up they are loaded.

I wonder if this is a good approach or maybe I'm trying to overcomplicate everything?

Upvotes: 0

Views: 944

Answers (3)

Colin
Colin

Reputation: 3752

Why waste bandwidth? Do this:

in UITableViewControllerDataSource::cellForRowAtIndexPath: start a timer to go off in, say 200 ms or something, which will begin the download process when it's triggered. Associate the timer with the indexPath (or cell).

In UITableViewControllerdelegate::tableView:didEndDisplayingCell:: kill the timer if it hasn't already gone off.

Upvotes: 1

nzeltzer
nzeltzer

Reputation: 521

Check out the UITableViewDelegate Protocol Reference.

Specifically, you can use the following methods to track cells' appearance and disappearance:

– tableView:willDisplayCell:forRowAtIndexPath:

- tableView:didEndDisplayingCell:forRowAtIndexPath:

Upvotes: 2

sha
sha

Reputation: 17860

There is a method of UITableViewCell that you can override: prepareForReuse. It will get called when table view is no longer need this cell and reusing memory for another cell that is becoming visible.

I think it will be a good start for you to cancel request associated with this cell.

Upvotes: -1

Related Questions