tags:

views:

1467

answers:

2

I'm trying to get an image from an URL and it doesn't seem to be working for me. Can someone point me in the right direction?

Here is my code:

NSURL *url = [NSURL URLWithString:@"http://myurl/mypic.jpg"];

NSString *newIMAGE = [[NSString alloc] initWithContentsOfURL:url
                                       encoding:NSUTF8StringEncoding error:nil];

cell.image = [UIImage imageNamed:newIMAGE];

When I debug the newIMAGE string is nil so something isn't working there.

A: 

Ok there's a couple of things wrong here:

  1. The conversion from URL (url) to NSString (newImage) is incorrect, what the code actually does there is try to load the contents of "http://myurl/mypic.jpg" into the NSString.

  2. The -imageNamed method takes a string that is a path of a local file, not a URL as an argument.

You need to use an NSData object as an intermediary, like in this example: http://blogs.oreilly.com/digitalmedia/2008/02/creating-an-uiimage-from-a-url.html

Justicle
+4  A: 

What you want is to get the image data, then initialize a UIImage using that data:

NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: @"http://myurl/mypic.jpg"]];
cell.image = [UIImage imageWithData: imageData];
[imageData release];
Jim Dovey
Thanks. That worked
TheGambler