【问题标题】:UIImage asynchronously is not loadingUIImage 异步未加载
【发布时间】:2016-01-16 03:39:18
【问题描述】:

我想从 url 获取图像,我正在这样做:

for(int i = 0; i < 50; i++)
{NSString *MyURL=[NSString stringWithFormat:@"http://*********/tatoo/%@/%@%d.png" ,@"b",@"b",i+1];


    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^(void) {
        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:MyURL]];

                             UIImage* image = [[UIImage alloc] initWithData:imageData];
                             if (image) {
                                 dispatch_async(dispatch_get_main_queue(), ^{
                                     [tmp addObject:image];
                                 });
                             }
                             });

}

images = [[NSArray alloc]initWithArray:tmp];

Url 为 valide ,但 tmp 为空。知道这里有什么问题吗?任何帮助将不胜感激!

【问题讨论】:

  • 什么时候空?显示代码
  • @Wain 当我想添加到图像数组时为空

标签: ios objective-c image url asynchronous


【解决方案1】:

您可以使用 AsyncImageView 加载图像而不会影响您的 UI。

从以下位置下载第三方类 https://github.com/nicklockwood/AsyncImageView

    AsyncImageView *storeImage = [[AsyncImageView alloc]init];

 //This will load any no logo image first. If url is dead then also it will work
     storeImage.image =[UIImage imageNamed:@"no-logo.png"];


  NSString *UrlSTR = @"ANY_IMAGE_URL";
  NSURL *imageURL = [NSURL URLWithString:UrlSTR];
  storeImage.contentMode = UIViewContentModeScaleAspectFit;
  storeImage.imageURL = imageURL;

这将在后台加载您的图片。

【讨论】:

  • 我按照你说的做了,但是来自 url 的图片没有加载。我用它来在我的数组中添加图像。 [tmp addObject:storeImage.image];没事吧?
  • 没有上面的代码会直接将图片添加到imageview中
  • 将图像添加到数组中有什么特别之处?无论如何,您将在某些图像视图中显示它吗?
  • 你知道如果我不向下滚动图片为什么不显示吗?
  • 第一个逻辑中的tmp数组你初始化了吗?
【解决方案2】:

异步下载尚未完成,需要等待。

使用操作队列或调度组等到它们都完成后,您就可以使用数组了。

还请注意,您不能保证数组中图像的任何顺序,因为您不知道每次下载需要多长时间。另外,最好不要同时启动 60 次下载...

【讨论】:

    【解决方案3】:

    你在添加图片数据之前初始化tmp了吗?

    tmp =[NSArray alloc]init];
    

    在for循环之前初始化

    【讨论】:

      猜你喜欢
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 2014-12-28
      • 2019-04-02
      • 1970-01-01
      • 2013-08-02
      • 2014-02-25
      • 1970-01-01
      相关资源
      最近更新 更多