Please consider subscribing to Mobile Developer Tips RSS feed or following us on Twitter
|
|
|
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://mobiledevelopertips.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://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
[self.view addSubview:[[UIImageView alloc] initWithImage:image]];
Related posts:
- How to Mask an Image
- Save an Image to Camera Roll
- How to download and process GZip’d data
Comments
5 Responses to “Download, Create and Display an Image from URL”
Leave Comment
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.
[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.
[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:
[Reply]
thanks
[Reply]
Thanks!
[Reply]