Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSURLSession to download a lot of images

I have created a simple testing app to learn how to use NSURLSession. This App has to download images from a webservice and present them into a UITableView. I've already written the first part of the App that reads a list of images urls from the web service, now, I want to display this list.

My doubt is:

given that the list of images could be a really long list, is it ok to create a NSURLSessionDownloadTask for each image? I thought to create the session in the cellForRowAtIndexPath function and store the NSURLSessions in a NSDictionary using as key the IndexPath of the cell (and probably relying on NSURLCache to avoid to download the same images more than once).

Other solutions:

I can see three more solutions:

  1. Using GCD with dispatch_async

  2. Subclassing NSOperation and essentially store an NSOperation for any image I need to download.

  3. Using a third party library like AFNetwork... but since it is a learning purpose app I prefer to go completely with my code .

If the multiple NSURLSession isn't a good solution, I'd choose one of those options.

What do you think about this approach?

like image 592
MatterGoal Avatar asked Jan 27 '26 05:01

MatterGoal


1 Answers

NSURLSessionTask is fine for a large number of downloads. One advantage of it over some of the other methods you mentioned is that downloads can be cancelled or paused. It also correctly implements concurrency for network operations, which is more difficult than many cats on the internet will lead you to believe (if you don't believe me, view the eskimo's 2010 WWDC session and sample code. NSOperation for network connections is not trivial).

NSURLSessionTask and friends are designed for exactly the kinds of problems you are trying to solve, and it's very well tested.

For a tableview, start the task in tableView:willDisplayCell:forRowAtIndexPath: and cancel (or pause) a task in tableView:didEndDisplayingCell:forRowAtIndexPath:. That will limit the active downloads to the currently visible cells.

like image 120
quellish Avatar answered Jan 29 '26 18:01

quellish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!