如何使用 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 的 NSURLConnection
与 cellForItemAtIndexPath
方法结合起来,以便在下载每个图像后立即将其加载到单元格中?
子类化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/