Ios – Getting images from url in Table View asynchronously

iosnsurlconnectionuitableview

So I am developing an app which contains a table view that has images in cells. I download all these images from a URL and store them in an array. I need to load these images asynchronously so I decided to use NSURLConnectionDataDelegate. I tried this code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    NSUInteger row = [indexPath row];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[URLsArray objectAtIndex:row]]];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        receicedData = [[NSMutableData alloc] init];
    } else {
        NSLog(@"Failed.");
    }
    return cell;
}

But it doesn't work. And I don't know what to write in:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

to set images to imageViews in cells. Can anyone help?

Best Answer

I would highly recommend using AFNetworking simply because it takes care of these kind of concerns.

At the very least, take a look at their UIImageView category as it allows you to do this:

UIImageView *imgView = //alloc, get it from a nib, whatever;
[imgView setImageWithURL:[NSURL URLWithString:@"StringPath"]];
Related Topic