Deekor
Deekor

Reputation: 9499

Quick image downloading

In my app I need to download several images, the images are 60kb tops.

The way I have been going about this is:

image.Image = UIImage.LoadFromData (NSData.FromUrl (new NSUrl("http://url")));

This works but takes an unexpectedly long time to download the images. Is there a better / faster way to be going about this that I don't know about?

The image downloading occurs in the ViewDidLoad () method which leads to an uncomfortably long pause before segueing to this view controller.

Upvotes: 1

Views: 209

Answers (2)

poupou
poupou

Reputation: 43553

A quick and dirty approach (adapted from some code I have) using the same API would be:

// Show a "waiting / placeholder" image until the real one is available
image.Image = ...
UIImage img = null;
// Download the images outside the main (UI) thread
ThreadPool.QueueUserWorkItem (delegate {
    UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
    using (NSUrl nsurl = new NSUrl (url))
    using (NSData data = NSData.FromUrl (nsurl)) {
        UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
        // we might not get any data, e.g. if there's no internet connection available
        if (data != null)
            img = UIImage.LoadFromData (data);
    }
    // finally call the completion action on the main thread
    NSRunLoop.Main.InvokeOnMainThread (delegate {
        // note: if `img` is null then you might want to keep the "waiting"
        // image or show a different one
        image.Image = img;
    });
});

Another thing that might help is to cache the images you download (e.g. offline mode) - but that might not be possible for your application.

In such case you would check if the cache has your image first and if not make sure you save it after downloading it (all of it done in the background thread).

Upvotes: 1

Jason
Jason

Reputation: 89102

MonoTouch.Dialog includes an ImageLoader (sec 5.3) class that will handle background loading of images, and can assign a default image while the "real" image is being downloaded. It may not necessarily be faster, but it should appear more responsive to the user.

image.Image = ImageLoader.DefaultRequestImage( new Uri(uriString), this)

As @poupou notes, the 2nd argument needs to be a reference to a class implementing IImageUpdated.

Upvotes: 2

Related Questions