views:

2208

answers:

2

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

+4  A: 

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];
Dave DeLong
thank you very much i didn't know how UIImageView worked! it was so simple! Thank you very much!
Antonio Murgia
A: 

Try this

NSURL *url = [NSURL URLWithString:@"http://192.168.1.2x0/pic/LC.jpg"];
 NSData *data = [NSData dataWithContentsOfURL:url];
UIImageView *subview = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,320.0f, 460.0f)];
[subview setImage:[UIImage imageWithData:data]]; 
[cell addSubview:subview];
[subview release];

All the Best.

Warrior