Thursday, May 3, 2012

Background Image Downloading with MonoTouch.Dialog ImageLoader

MonoTouch.Dialog contains a very useful class called ImageLoader to perform background image downloading like iTunes and AppStore.

ImageLoader does not have a DefaultImage property though which I need in my app to display as a placeholder before the actual image gets downloaded or if the download failed. You will need to do a little extra work to assign a default image.

First a little background on how ImageLoader works. ImageLoader caches downloaded images automatically (defaults to 50 images) so calling ImageLoader.DefaultRequestImage will either return a null if the image is not cached or the actual UIImage object if the image is cached. In the former case ImageLoader will queue a download request for the image and then call the interface method UpdatedImage when the download succeeds.

What happens when the download failed though? ImageLoader does NOT call UpdatedImage if the download failed. So you can't assign the your default image there because nothing will be done.

Instead, you should assign your default image immediately after the first call to DefaulRequestImage.

var cover = ImageLoader.DefaultRequestImage(uri, this);

if(cover == null)
{
_ImageView.Image = DefaultImage;
}
else 
{
_ImageView.Image = cover;
}

If the image is cached, your ImageView will display the real image. If it's not the default image will be displayed. In the UpdatedImage callback method, you should just do the following:

#region IImageUpdated implementation
public void UpdatedImage (Uri uri)
{
_ImageView.Image = ImageLoader.DefaultRequestImage(uri, this);
}
#endregion

In the case where download succeeded, this will get called and your default image will be replaced with the real image. If download failed, this method won't get called and your default image stays.

I will post a full sample soon.

You can check the official doco here:
http://docs.xamarin.com/ios/tutorials/MonoTouch.Dialog#Background_Image_Loading

And the actual code for ImageLoader.cs can be found here:
https://github.com/migueldeicaza/MonoTouch.Dialog/blob/master/MonoTouch.Dialog/Utilities/ImageLoader.cs