Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: How to get a UIImage from a url?

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

like image 270
philfreo Avatar asked Nov 19 '09 04:11

philfreo


People also ask

How do I find my UIImage path?

Once a UIImage is created, the image data is loaded into memory and no longer connected to the file on disk. As such, the file can be deleted or modified without consequence to the UIImage and there is no way of getting the source path from a UIImage.

How do I download an image from Swift?

Select New > Project... from Xcode's File menu and choose the Single View App template from the iOS > Application section. Name the project Images and set User Interface to Storyboard. Leave the checkboxes at the bottom unchecked. Tell Xcode where you would like to save the project and click the Create button.

What is UIImage?

An object that manages image data in your app.


3 Answers

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

However, this isn't asynchronous.

like image 173
philfreo Avatar answered Oct 21 '22 20:10

philfreo


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)
    {
        self.image = [[[UIImage alloc] initWithData:requestData] autorelease];
    }
}

Where requestData and image are instance variables of your containing class, and image is a retained property. Be sure to release image in the dealloc routine of the class, e.g. using self.image=nil;.

like image 23
Matt Long Avatar answered Oct 21 '22 20:10

Matt Long


It is true that Asynchronous loading is a must, but you can also achieve that with a background call if you just need a simple solution.

[self performSelectorInBackground:@selector(loadImage) withObject:nil];

- (void)loadImage
{
   NSURL * url = [NSURL URLWithString:@"http://.../....jpg"];
   NSData * data = [NSData dataWithContentsOfURL:url];
   UIImage * image = [UIImage imageWithData:data];
   if (image)
   {
       // Success use the image
       ...
   }
   else
   {
       // Failed (load an error image?)
       ...
   }
}   
like image 23
Rivera Avatar answered Oct 21 '22 19:10

Rivera