views:

504

answers:

3

How do you download an image and turn it into a UIImage?

+2  A: 
NSURL *url = [NSURL URLWithString:@"http://example.com/image.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
philfreo
+3  A: 

You should keep in mind that loading the image data with the sample code you've provided in your own answer will block the main thread until the download has completed. This is a useability no-no. The users of your app will think your app is unresponsive. If you want to download an image, prefer NSURLConnection to download it asynchronously in its own thread.

Read the Apple documentation about async downloads with NSURLConnection.

When your download completes, you can then instantiate your UIImage from the data object:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (requestData)
    {
        image = [[UIImage alloc] initWithData:requestData];
    }
}

Where requestData and image are instance variables of your containing class.

Matt Long
Excellent point. I was just looking at this also: http://www.markj.net/iphone-asynchronous-table-image/
philfreo
A: 

A problem I'm running into here is when I try to initialize set img to a UIImageView, I get an NSInvalidArgumentException, the reason being [UIView setImage:] unrecognized selector. Any thoughts?

Pat
Please read the FAQ of StackOverflow... create a new question rather than posting an answer.
philfreo