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
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.
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.
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];
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
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