通过经过身份验证的NSURLConnection下载UICollectionViewCell图像

时间:2014-02-20 17:05:34

标签: ios objective-c nsurlconnection uicollectionview basic-authentication

如何使用HTTP基本身份验证从服务器下载多个小图像,并将它们异步加载到UICollectionView。下面的代码适用于没有任何身份验证的服务器,但文件将存储在Basic身份验证之后。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    BrowseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];

    int row = [indexPath row];

    NSString *fileName = [files objectAtIndex:row]; //NSArray *files
    NSString *filePath = [thumbDir stringByAppendingPathComponent:fileName];

    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^{
            NSString *strURL = [NSString stringWithFormat:@"http://www.somethng.com/thumbs/%@", fileName];
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
            [data writeToFile:filePath atomically:YES];
            dispatch_sync(dispatch_get_main_queue(), ^{
                if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
                    cell.imageView.image = [UIImage imageWithContentsOfFile:filePath];
                [cell setNeedsLayout];
            });
        });
        cell.imageView.image = [UIImage imageNamed:@"placeholder.png"];
    }
    else
    {
        cell.imageView.image = [UIImage imageWithContentsOfFile:filePath];
    }
    cell.imageName = fileName;

    return cell;
}

如何将NSURLConnection(涵盖authenticationChallenge)与cellForItemAtIndexPath方法合并,以便在下载后立即将每个图片加载到单元格中?

继承NSURLConnectionDelegate并发送indexPath从其他类中重新加载单元格是否有意义?有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

就个人而言,我在下载和缓存图片时使用this library。实现非常简单:

cell.imageView setImageWithURL:[NSURL URLWithString:[[NSString stringWithFormat:@"http://www.somethng.com/thumbs/%@", fileName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];

图书馆将为您缓存图像。如果您需要知道何时加载图像,也可以使用库中的块方法。