Objective-c – Xcode iPhone Programming: Loading a jpg into a UIImageView from URL

iphoneobjective cuiimageviewurlxcode

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

Best Answer

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