Jones
Jones

Reputation: 375

Displaying an image from a URL

I've got the URL of an image (http://www.example.com/logo.png), but I don't know how to use that to display the image.

I'm "pushing" the URL from my table view controller to a detail controller with a variable called selectedImage

I guess it should be something like this:

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 104)];
[imageView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"%@", selectedImage]]];
[self.view addSubview:imageView];

[self.view sendSubviewToBack:imageView];

but that doesn't display the image.

Upvotes: 0

Views: 159

Answers (3)

Antonio MG
Antonio MG

Reputation: 20410

You only need to do this:

NSURL *url = [NSURL URLWithString:@"http://i0.kym-cdn.com/entries/icons/original/000/005/545/OpoQQ.jpg?1302279173"];
NSData *data = [NSData dataWithContentsOfURL:url];
imageView.image = [[[UIImage imageWithData:data];

Upvotes: 2

Mario
Mario

Reputation: 4520

As I understand, it is a remote file with a URL to an image? UIImage imageNamed won't work then.

Use

[UIImage imageWithContentsOfFile: ....]

if file is on phone, or imageWithData and dataWithContentsOfURL (or even better asynchronous download)

cheers

Upvotes: 0

Christian Schnorr
Christian Schnorr

Reputation: 10786

Once you have the image as a UIImage you can just set it as the image view's image property.

imageView.image = yourImage;

No need for a background color.

Upvotes: 0

Related Questions