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

标签 ios objective-c nsurlconnection uicollectionview basic-authentication

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

- (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以从其他类中重新加载单元格是否有意义?有更好的方法吗?

最佳答案

我个人使用 this library当我下载和缓存图像时。实现非常简单:

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

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

关于ios - 通过经过身份验证的 NSURLConnection 下载 UICollectionViewCell 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21914731/

相关文章:

ios - 应用内购买后,viewWillAppear 会多次加载已购买的项目

ios - 将 UITextView 文本转换为 [String],将段落分隔为字符串

ios - 如何在 ios 应用程序商店的 Release模式下构建 React Native 应用程序?

iphone - 如何在 NSMutableUrlRequest 中发布文本和图像数据?

iphone - NSURLConnection、基本身份验证和 Cookie 问题

ios - Objective C 中 iOS 的图像模糊检测

ios - 从另一个应用程序 ios 链接到设置应用程序的声音部分

ios - 单击时如何检查 ImageView 标签

objective-c - 在 Objective C 中声明和初始化字符串变量的最佳方式

ios - NSURLSession 方法在登录时返回 true 或 false