ios - 将图像从 Web 服务加载到 UIImage 无法正常工作

标签 ios objective-c uiimage nsdata dispatch-async

我有一个包含 url 作为数组元素的 productImageArray。 我正在尝试在我的 ImageView 中加载这些 url。

以下是我加载它的方式。

UIActivityIndicatorView *spinner=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        spinner.center=CGPointMake(160.0,240.0 );
        spinner.hidesWhenStopped=YES;
        [self.view addSubview:spinner];
        [spinner startAnimating];

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
        dispatch_async(queue, ^{
             NSData *storeImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productImageArray[indexPath.row]]];
            self.productImage.image = [UIImage imageWithData:storeImageData];
            dispatch_sync(dispatch_get_main_queue(), ^{

                [spinner stopAnimating];
            });
        });

问题在于,

  1. 只有我的 tableview 的最后一个单元格加载图像,而其余单元格不从 url 加载图像
  2. 是否有任何其他更好的方法可以使用 native 方法将图像从 url 直接加载到我的 UIImage 中?

当我使用以下代码时,我的 tableview 的每个单元格都会加载图像数据,但它仍然会卡住用户界面,直到数据完全加载为止

NSData *storeImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productImageArray[indexPath.row]]];

        self.productImage.image = [UIImage imageWithData:storeImageData];

最佳答案

@Anbu.Karthik 的回答是正确的。

但是,也许最简单的解决方案是使用类似 SDWebImage 的东西,不是吗?这个库将处理这个问题以及更多(缓存、错误管理、适当的 tableview 单元格处理,...)。

我认为您至少应该花几分钟时间看一下:https://github.com/rs/SDWebImage

编辑:

如果您使用 SDWebImageUIActivityIndi​​cator-for-SDWebImage,您可以将整个代码替换为:

   [self.productImage setImageWithURL:[NSURL URLWithString:productImageArray[indexPath.row]]
                      usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

关于 UIActivityIndi​​cator-for-SDWebImage 的更多信息:https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage

关于ios - 将图像从 Web 服务加载到 UIImage 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37086044/

相关文章:

ios - 添加新的自定义 UIButton 时,现有的自定义 UIButton 会变形

objective-c - 如果 subview 更改大小,则调整父 View 的大小

ios 11 应用程序的颜色 (uinavigation)

ios - SVG 字符串到 iOS 的 UIImage

objective-c - 如何获得左对齐的cocos2d菜单

ios - 证书 : Unknown, 配置文件 : None in xcode 10. 1 个存档

ios - UIStackView 和 Fill Distribution - 不尊重内容拥抱优先级

ios - UIWebView上的PDF

ios - 具有可调整大小的图像的 UIButton

ios - UI 图像/多 View Controller