如何使用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以从另一个类中重新加载单元是否有意义?有没有更好的方法呢?
发布于 2014-02-21 02:13:31
就我个人而言,我在下载和缓存图像时使用this library。实现起来很简单,就像:
cell.imageView setImageWithURL:[NSURL URLWithString:[[NSString stringWithFormat:@"http://www.somethng.com/thumbs/%@", fileName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];该库将为您缓存图像。如果您需要知道图像何时加载,也可以使用库中的block方法。
https://stackoverflow.com/questions/21914731
复制相似问题