Loading image from URL on iPhone

2019-08-05 15:17发布

问题:

I have no idea why this isn't working.

NSData *data = [NSData dataWithContentsOfURL:place.iconData];
UIImage *image = [UIImage imageWithData:data];
[imageView setImage:image];

imageView is an IBOutlet hooked up through IB. place.iconData is http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png. For some reason, though, it won't load. Any help is much appreciated.

回答1:

Is your data being freed before it got assigned?

Maybe try manually allocating memory for the NSData:

NSData *data = [[NSData alloc] initWithContentsOfURL:place.iconData];
UIImage *image = [[UIImage alloc] initWithData:data];
[imageView setImage:image];

[data release];
[image release];


回答2:

Try this:

NSURL *url = [NSURL URLWithString: @"http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png"];

NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[imageView setImage:image]; 
//or imageView.Image=image;


回答3:

You need to use NSURL. Follow this url http://iosdevelopertips.com/cocoa/download-and-create-an-image-from-a-url.html