Getting Image from URL Objective C

Viewed 96118

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.

5 Answers

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

As requested, here's an asynchronous version:

dispatch_async(dispatch_get_global_queue(0,0), ^{
    NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: @"http://myurl/mypic.jpg"]];
    if ( data == nil )
        return;
    dispatch_async(dispatch_get_main_queue(), ^{
        // WARNING: is the cell still using the same data by this point??
        cell.image = [UIImage imageWithData: data];
    });
    [data release];
});

Updating upon Jim dovey answer,[data release] is no longer required because in the updated apple guidelines. Memory management is done automatically by ARC (Automatic counting reference) ,

Here is the updated asynchronous call,

dispatch_async(dispatch_get_global_queue(0,0), ^{
        NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: @"your_URL"]];
        if ( data == nil )
            return;
        dispatch_async(dispatch_get_main_queue(), ^{
            self.your_UIimage.image = [UIImage imageWithData: data];
        });

    });
Related