What if images on the iPhone were as easy as HTML?

Shaun, Oct 20

HTML is great, you want to set an image and you do <img src="http://example.com/image.jpg" />. It does everything else for you, it caches, it even loads in the background. This is something that is taken completely for granted until you actually have to do it yourself.

The work involved in doing this on the iPhone is a pain. It's not so bad if you're viewing a single image, but if you're displaying web-based images in a table view? Ugh.

Enter EGOImageLoading.

We created EGOImageLoading to be as easy to use as HTML. EGOImageLoading is a few classes to make life easier on the developer, and to give the end user a much smoother result, easily.

Here's what EGOImageLoading does:

  • It loads the image in the background
  • It caches the image to the disk for you
  • It allows you to set a placeholder image while it's loading

And here's where it gets even more awesome: It changes loading priorities on the fly. If the user scrolls a bit in the table view, it'll decrease the priority of those images, and load the ones they're looking at right now, first.

So how simple is this? You can jump to our GitHub page and grab the demo, but here's what our UITableViewCell subclass looks like:

Yeah, it really is that simple.

So how does it work?

It's all based on EGOImageLoader and EGOCache.

We published EGOCache a few months ago, and we've since improved it to work better with EGOImageLoader.

EGOImageLoader does all the heavy lifting. It checks to see if the image is cached, if it is, you get it right away. If not, it loads it up in the background, and if it's told to, it decreases the priorities and bumps new loads to the top.

You can use EGOImageLoader without table views, and it'll work great. However, this post is all about table views, so we created UIImageView and UIButton subclasses, EGOImageView and EGOButton respectively, that interact with EGOImageLoader for you. That means all you have to do is initialize them, and set the URL. Seriously, that's it.

They both contain "increaseImageLoadPriority" and "decreaseImageLoadPriority".

You'll probably never need to increase priority, since it does that for you when it loads (or re-sets a loading URL). However, you are going to want to decrease the load priority once the table view cell is moved off screen, we do this in the above example by tracking willMoveToSuperview.

So there you have it, image loading on the iPhone, that's just as easy as throwing in an HTML image tag.

You can grab EGOImageLoading on it's GitHub page: http://github.com/enormego/EGOImageLoading

Also a quick note, EGOImageLoader is powered by the awesome ASIHTTPRequest class by Ben Copsey. I'm sure you could rework it to work with NSURLConnection, but why? ASIHTTPRequest is amazing. If you're not using it, you should be.

blog comments powered by Disqus