Download, Create and Display an Image from URL

November 4, 2009

This tip will show the steps to download and display an image from a remote resource. This is handy if you need to add an image as a subview, yet, the image is not part of your application bundle.

URL to Remote Image

We start by creating a URL to the remote resource:

NSURL *url = [NSURL URLWithString: 
   @"http://iosdevelopertips.com/images/logo-iphone-dev-tips.png"];
Create UIImage from NSData

The next step is to build a UIImage using the data downloaded from the URL, which consists of an NSData object that holds the remote image contents:

UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
Putting it Together

Here’s how to wrap it all together, adding the remote image as a subview to an existing view by creating a UIImageView from the above UIImage:

NSURL *url = [NSURL URLWithString: 
   @"http://iosdevelopertips.com/images/logo-iphone-dev-tips.png"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 
[self.view addSubview:[[UIImageView alloc] initWithImage:image]];

6 comments

The problem this code is that the fetch happens synchronously. If this is called in the UI thread, the app will appear block while the image is being fetched.

The fetch should happen on a background thread.

by Paul Westbrook on Nov 4, 2009. Reply #

The problem with this approach is that this will block the UI thread until the image is downloaded. I would suggest using EGOImageLoading by Enormego for example http://url.akosma.com/sz9xb which loads the image in a background thread, and even caches it so that later it’s retrieved from the local disk.

by Adrian on Nov 4, 2009. Reply #

Paul / Adrian,

Good call on the background thread…in cases such as this, I typically request the synchronous code to run in a new thread, something similar to the following:

- (void) loadImageInBackground
{
  NSURL *url = [NSURL URLWithString: 
     @"http://iphonedevelopertips.com/images/logo-iphone-dev-tips.png"];
 
  // Assume image is an instance variable
  image = [[UIImage imageWithData: [NSData dataWithContentsOfURL:url]] retain];
}
 
...
 
[NSThread detachNewThreadSelector:@selector(loadImageInBackground)
   toTarget:self withObject:nil];
 
...
 
[self.view addSubview:[[UIImageView alloc] initWithImage:image]];

by John Muchow on Nov 4, 2009. Reply #

thanks

by book on Nov 25, 2009. Reply #

Thanks!

by HockeyBias.com on Sep 27, 2011. Reply #

Thx u man

by wiralim on Nov 29, 2012. Reply #

Leave a Comment