ios - 如何在 NSURLConnection 委托(delegate)完成后更新 UIImages

标签 ios objective-c nsurlconnection lazy-loading

所以我使用 NSURLConnection 从我的 API 中提取了大约 50 个图像,它工作得很好,除了它在运行时锁定了 UI。我假设这是因为我正在从 NSURLConnection self 委托(delegate)中实时更新 UI。所以我想我需要做的是将占位符加载图像放在 UIImage 中,然后在委托(delegate)获取所有数据后以某种方式更新它们,但是我该怎么做,有人可以给我一些编码示例吗?

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now

    NSData *imageData = _dataDictionary[ [connection description] ];

    if(imageData!=nil)
    {
    NSLog(@"%@%@",[connection description],imageData);

    UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(self.x, 0, self.screenWidth, self.screenHight)];

    // Process thi image
    // resize the resulting image for this device
    UIImage *resizedImage = [self imageScaleCropToSize:[UIImage imageWithData: imageData ]];

    self.x = (self.x + imageView.frame.size.width);
    if(self.x > self.view.frame.size.width) {
        self.scrollView.contentSize = CGSizeMake(self.x, self.scrollView.frame.size.height);
    }

    [imageView setImage:resizedImage];
    // add the image
    [self.scrollView addSubview: imageView];
    }
}

最佳答案

您可以使用 SDWebImage图书馆来实现这一目标。

假设 imageArray 有所有的图片 url 路径。 您可以使用 SDWebImageManager 下载所有图像并在 ImageView 中显示它们。您还可以使用此 block 显示下载进度。

- (void)showImages:(NSArray *)imageArray
{
  SDWebImageManager *manager = [SDWebImageManager sharedManager];
  for (NSString *imagePath in imageArray)
  {
      [manager downloadImageWithURL:[NSURL URLWithString:imagePath]
                          options:SDWebImageLowPriority
                         progress:^(NSInteger receivedSize, NSInteger expectedSize){}
                        completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL)
         {

           if(!error)
               self.imgView_Image.image = image;
           else
            {
               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"please check your  Connection and try again"  message:@"No Internet Connection" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles: nil];
               [alert show];
            }
         }];
  }
}

关于ios - 如何在 NSURLConnection 委托(delegate)完成后更新 UIImages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30708925/

相关文章:

ios - Phonegap App Store 提交 : ITMS-90683: Missing Purpose String in Info. plist - NFCReaderUsageDescription - 不使用插件

c# - 如何使用 C# 访问 iOS App 的文档文件夹

objective-c - id 类型实例变量向实例方法发送消息

ios - 如何将 UITableViewCell 放到 UITableView 的底部。

swift - 在 Swift 中检索网络字符串

ios - 为什么在单独的线程中使用异步 HTTP 请求而不是同步 HTTP?

iOS UILabel 旋转问题

iOS swift : Separate AppDelegate for XCTest

objective-c - Cocoa:NSTableView重复加载单元格中标签的数据

objective-c - 在 iPhone 模拟器上测试互联网连接