Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode iPhone Programming: Loading a jpg into a UIImageView from URL

Tags:

My app has to load an image from a http server and displaying it into an UIImageView
How can i do that??
I tried this:

NSString *temp = [NSString alloc]; [temp stringwithString:@"http://192.168.1.2x0/pic/LC.jpg"] temp=[(NSString *)CFURLCreateStringByAddingPercentEscapes(     nil,     (CFStringRef)temp,                          NULL,     NULL,     kCFStringEncodingUTF8) autorelease];   NSData *dato = [NSData alloc];  dato=[NSData dataWithContentsOfURL:[NSURL URLWithString:temp]];  pic = [pic initWithImage:[UIImage imageWithData:dato]]; 

This code is in viewdidload of the view but nothing is displayed! The server is working because i can load xml files from it. but i can't display that image!
I need to load the image programmatically because it has to change depending on the parameter passed! Thank you in advance. Antonio

like image 523
Antonio Murgia Avatar asked Mar 24 '10 18:03

Antonio Murgia


People also ask

How do I make an image appear in Xcode?

There are two ways to add an image to Xcode project. First one is to drag and drop an image file from Finder onto the assets catalog. Dragging the image will automatically create new image set for you. Drag and drop image onto Xcode's assets catalog.

How do I download an image from Swift 5?

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.


2 Answers

It should be:

NSURL * imageURL = [NSURL URLWithString:@"http://192.168.1.2x0/pic/LC.jpg"]; NSData * imageData = [NSData dataWithContentsOfURL:imageURL]; UIImage * image = [UIImage imageWithData:imageData]; 

Once you have the image variable, you can throw it into a UIImageView via it's image property, ie:

myImageView.image = image; //OR [myImageView setImage:image]; 

If you need to escape special characters in your original string, you can do:

NSString * urlString = [@"http://192.168.1.2x0/pic/LC.jpg" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; NSURL * imageURL = [NSURL URLWithString:urlString]; .... 

If you're creating your UIImageView programmatically, you do:

UIImageView * myImageView = [[UIImageView alloc] initWithImage:image]; [someOtherView addSubview:myImageView]; [myImageView release]; 
like image 99
Dave DeLong Avatar answered Oct 14 '22 07:10

Dave DeLong


And because loading image from URL takes ages, it would be better to load it asynchronously. The following guide made it stupid-simple for me:

http://www.switchonthecode.com/tutorials/loading-images-asynchronously-on-iphone-using-nsinvocationoperation

like image 20
nosuic Avatar answered Oct 14 '22 06:10

nosuic