【问题标题】:Getting images from url in Table View asynchronously从表视图中的 url 异步获取图像
【发布时间】:2011-11-21 19:52:54
【问题描述】:

所以我正在开发一个应用程序,其中包含一个表格视图,其中包含单元格中的图像。我从一个 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

将图像设置为单元格中的图像视图。有人可以帮忙吗?

【问题讨论】:

    标签: ios uitableview nsurlconnection


    【解决方案1】:

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

    至少,看看他们的UIImageView category,因为它允许你这样做:

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

    【讨论】:

    • 但是如果我使用setImageWithURL,它会同步加载图片,不是吗?如果是,如何使其异步?
    • 如果你点击文档链接,你会看到它清楚地表明图像将异步下载。
    • 好的,但是有什么办法不使用任何额外的库?
    • 我会让其他人发布该答案。对我来说,没有理由不通过使用可免费获得的经过验证的代码来减轻开发的痛苦。没有理由重新发明轮子。 :) (特别是当他们可以使用- setImageWithURL: 将你所有的问题和代码变成一行代码时!)
    • 它工作得很好)抱歉这么烦人,但我需要一个动画活动指示器,而不是在图片下载时。方法 setImageWithURL:placeholderImage: 允许显示图像,但我需要一个活动指示器。这将如何运作?
    【解决方案2】:

    对于更简单的解决方案,我建议使用Cached Image for iOS。这是一段简单的代码,您可以将其添加到您的 xcode 项目中,它可以满足您的需求(+ 支持缓存)。

    【讨论】:

      猜你喜欢
      • 2012-07-19
      • 1970-01-01
      • 2015-03-16
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 2015-01-29
      相关资源
      最近更新 更多