使用NSURLConnection异步下载UITableView的图像

时间:2016-03-28 09:41:35

标签: ios objective-c uitableview asynchronous

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

#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次下载。 但是,当我尝试使用队列实现代码时,它不会下载任何内容。我明白我做错了但是我无法定义它。

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

2 个答案:

答案 0 :(得分:2)

使用Apple中的示例代码来解决延迟加载的问题。

答案 1 :(得分:2)

如果你想要开始它的基础知识,我想你应该从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;
  });
});