How do you download an image and turn it into a UIImage?
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.
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.
An object that manages image data in your app.
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.
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;
.
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?)
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With