ios - 使用 NSURLConnection 异步下载 UITableView 的图像

标签 ios objective-c uitableview asynchronous

我有一个带有 customCells 的 TableView,当用户按下某个单元格上的开始按钮时,加载开始。有很多这样的单元,所以我需要并行(异步)实现这个下载。
对于图像下载和更新表格 View 中的单元格,我使用下一个代码:

#define myAsyncQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

我将此方法包含在异步队列中,我认为应该启用图像的并行下载。
- (void)didClickStartAtIndex:(NSInteger)cellIndex withData:
    (CustomTableViewCell*)data
    {
 dispatch_async(myAsyncQueue, ^{        
self.customCell = data;
        self.selectedCell = cellIndex;
        ObjectForTableCell* tmp =[self.dataDictionary objectForKey:self.names[cellIndex]];

        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:tmp.imeageURL]
                                                    cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                timeoutInterval:60.0];
        self.connectionManager = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
       }); 
    }
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
          self.urlResponse = response;

        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        NSDictionary *dict = httpResponse.allHeaderFields;
        NSString *lengthString = [dict valueForKey:@"Content-Length"];
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        NSNumber *length = [formatter numberFromString:lengthString];
        self.totalBytes = length.unsignedIntegerValue;

        self.imageData = [[NSMutableData alloc] initWithCapacity:self.totalBytes];
    }

    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
           [self.imageData appendData:data];
        self.customCell.progressView.progress = ((100.0/self.urlResponse.expectedContentLength)*self.imageData.length)/100;
          float per = ((100.0/self.urlResponse.expectedContentLength)*self.imageData.length);
        self.customCell.realProgressStatus.text = [NSString stringWithFormat:@"%0.f%%", per];

    }

   I tried to set this block to queue - main queue - cause its the place where image is already downloaded,

        -(void)connectionDidFinishLoading:(NSURLConnection *)connection
        {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.customCell.realProgressStatus.text = @"Downloaded";

            UIImage *img = [UIImage imageWithData:self.imageData];
            self.customCell.image.image = img;
            self.customCell.tag = self.selectedCell;
    });
            [self.savedImages setObject:img forKey:self.customCell.nameOfImage.text];
            NSNumber *myNum = [NSNumber numberWithInteger:self.selectedCell];
            [self.tagsOfCells addObject:myNum];
       }

没有所有队列(当我评论它时)一切正常 - 但只有 1 个下载。
但是当我尝试使用队列实现代码时,它不会下载任何东西。我知道我做错了,但我无法定义它。

非常感谢您提前提供的任何帮助。

最佳答案

如果你想从基础开始,我猜你应该从 NSURLSession 开始。作为 NSURLConnection大多数实现已被弃用,在 iOS 9 之后将不再可用。完整引用 URL Session Programming Guide tutorial

回到你的问题,你应该从教程中做类似的事情

// 1
NSURLSessionDownloadTask *getImageTask =
[session downloadTaskWithURL:[NSURL URLWithString:imageUrl]

    completionHandler:^(NSURL *location,
                        NSURLResponse *response,
                        NSError *error) {
        // 2
        UIImage *downloadedImage =
          [UIImage imageWithData:
              [NSData dataWithContentsOfURL:location]];
      //3
      dispatch_async(dispatch_get_main_queue(), ^{
        // do stuff with image
        _imageWithBlock.image = downloadedImage;
      });
}];

// 4
[getImageTask resume];

但我个人的建议是 AFNetworking最适合 iOS 网络并在 iOS 应用程序世界中广泛使用/测试。

使用 AFNetworking 下载图像
[_imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://i.imgur.com/fVhhR.png"]]
                      placeholderImage:nil
                               success:^(NSURLRequest *request , NSHTTPURLResponse *response , UIImage *image ){
                                   NSLog(@"Loaded successfully: %d", [response statusCode]);
                               }
                               failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
                                   NSLog(@"failed loading: %@", error);
                               }
    ];

编辑:使用并发进行异步下载
// get main dispact queue
dispatch_queue_t queue = dispatch_get_main_queue();
// adding downloading task in queue using block
dispatch_async(queue, ^{
  NSData* imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
  UIImage* image = [[UIImage alloc] initWithData:imageData];
  // after download compeletes geting main queue again as there can a possible crash if we assign directly
  dispatch_async(dispatch_get_main_queue(), ^{
    _imageWithBlock.image = image;
  });
});

关于ios - 使用 NSURLConnection 异步下载 UITableView 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36259673/

相关文章:

ios - SpriteKit 在使用 [Flurry startSession :FlurryAPPKey]; 进入背景时崩溃

ios - Swift 中的初始化器

ios - 如何像目标一样在圆圈内绘制多个圆圈并获取特定圆圈的触摸事件?

ios - 如何为 UITableView 标题设置颜色文本颜色

iphone - 如何使 UITableViewCells 被默认选中进行编辑

ios - WKWebView 打不开外部链接

ios - 在 SwiftUI 中,如何执行手势但将手势转发到它后面的 View ?

ios - 需要从支付 key PayPal 获得交易 ID

javascript - 使用 Parse JavaScript 定义两个用户之间的相互关系

swift - 如何为 UITableView 中的每个部分启用水平分页