首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过认证的NSURLConnection下载UICollectionViewCell镜像

通过认证的NSURLConnection下载UICollectionViewCell镜像
EN

Stack Overflow用户
提问于 2014-02-21 01:05:34
回答 1查看 91关注 0票数 0

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

代码语言:javascript
复制
- (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;
}

如何将涵盖authenticationChallenge的NSURLConnectioncellForItemAtIndexPath方法结合起来,以便在图像下载后立即将其加载到单元中?

NSURLConnectionDelegate子类化并发送indexPath以从另一个类中重新加载单元是否有意义?有没有更好的方法呢?

EN

回答 1

Stack Overflow用户

发布于 2014-02-21 02:13:31

就我个人而言,我在下载和缓存图像时使用this library。实现起来很简单,就像:

代码语言:javascript
复制
cell.imageView setImageWithURL:[NSURL URLWithString:[[NSString stringWithFormat:@"http://www.somethng.com/thumbs/%@", fileName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21914731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档