从表视图中的url异步获取图像



所以我正在开发一个应用程序,其中包含一个在单元格中有图像的表视图。我从一个URL下载所有这些图像,并将它们存储在一个数组中。我需要异步加载这些图像,所以我决定使用NSURLConnectionDataDelegate。我试过这个代码:

- (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;
}

但是它不起作用。我不知道该写什么:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

将图像设置为单元格中的imageViews。有人能帮忙吗?

我强烈推荐使用AFNetworking,因为它可以处理这些问题。

至少,看看他们的UIImageView类别,因为它允许您这样做:

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

对于一个更简单的解决方案,我建议在iOS上使用缓存图像。这是一段简单的代码,你可以添加到你的xcode项目,它做你需要的(+支持缓存)。

最新更新