UIImage loaded from URL in Xamarin / C#

Not a one-liner, but with very few lines you can roll your own. E.g.

static UIImage FromUrl (string uri)
{
    using (var url = new NSUrl (uri))
    using (var data = NSData.FromUrl (url))
        return UIImage.LoadFromData (data);
}

The calls, including the one from UIImage, are thread-safe.


With new await/async support you can do:

public async Task<UIImage> LoadImage (string imageUrl)
        {
            var httpClient = new HttpClient();

            Task<byte[]> contentsTask = httpClient.GetByteArrayAsync (imageUrl);

            // await! control returns to the caller and the task continues to run on another thread
            var contents = await contentsTask;

            // load from bytes
            return UIImage.LoadFromData (NSData.FromArray (contents));
        }

and you call this with:

someYourUIImageObjectOnUI.Image = await this.LoadImage ("some image url");

You want to be sure that you load the image async so that you do not block your UI thread. MonoTouch.Dialog includes an ImageLoader (see sec 5.3) class that you could use.

There are also a couple of variations of UrlImageStore out there to help with async loading images.

Finally, if you want to do it manually, there is a Xamarin Recipe you can use.