Nathan Schafer
Nathan Schafer

Reputation: 273

How to download images from array to tableviewcontroller in swift?

I have a table view controller with a cell that contains an UIImageView. I also have a NSMutableArray that contains the url's. I want the url's to download the images and place them in the correct order. The NSMutableArray also contains some empty Strings and the cell that it corresponds too I want to have my placeholder image from my image assets.

How can I get it to work? I have also populated each cell with a title and summary but cannot workout how images work.

UPDATE

The code used for the image download. Note the photoLabels contains the array of images. Some of the photos are in the incorrect place once the first placeholder image occurs (It is one index late). Why is it doing that. Does anyone know why. I have println(photoLabels) and all the 50 strings are correct (with some just being "")

If anyone can help that would be great.

let imageURL: String = photoLabels.objectAtIndex(indexPath.row) as String
println(imageURL)
if imageURL == "" {
    cell.imageContainer.image = UIImage(named: "placeholder")
} else {
    cell.imageContainer.setImageWithURL(NSURL(string: imageURL))
}

return cell

Thanks

Upvotes: 1

Views: 919

Answers (1)

Rob
Rob

Reputation: 437432

This seemingly innocent question actually entails a rat's nest of interesting details. These include:

  • Use lazy loading of the image, loading them just-in-time, rather than trying to download them up front;
  • Download the images asynchronously;
  • While downloading the images as needed, cache them (using NSCache, not NSMutableArray) so that if you scroll back to see some images recently downloaded that you don't have to download them again;
  • But, in response to memory pressure, make sure to empty the RAM-based cache (but still avail yourself of the persistent storage cache);
  • If user scrolls quickly down to the 100th row in the table example, make sure that the images for the visible cells don't get backlogged behind the requests for the previous 99 images (nb: you should test your app in suboptimal conditions, e.g. a poor 2G or 3G cellular environment, which can be simulated with the network link conditioner); and
  • You might want a placeholder image to show until the asynchronously retrieved image is downloaded (or retrieved from the cache).

The bottom line is that this takes a non-trivial amount of effort to do properly. As a result, I'd encourage you to use an existing solution, for example the UIImageView categories that are available from SDWebImage or AFNetworking. Both of these two frameworks offer a nice category for UIImageView that allows you to request the image to be downloaded asynchronously (it's sd_setImageWithURL in SDWebImage; it's setImageWithURL in AFNetworking).

Upvotes: 1

Related Questions