要求:
我有一个视图控制器类,我在其中显示一个集合视图。在每个单元格中,我正在检查图像是否已存在于本地,如果它不存在,那么我试图从服务器下载图像并显示相同的图像。
实施
以下是相同的代码:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
// retrieving associated product
Products *aProduct = [self.fetchedResultsController objectAtIndexPath:indexPath];
UICollectionViewCell* newCell = [self.collectionView dequeueReusableCellWithReuseIdentifier:kProductIconIdentifier forIndexPath:indexPath];
// setup of image view and cell label
UIImageView *cellImageView = (UIImageView *)[collectionView viewWithTag:kImageViewTag];
cellImageView.contentMode = UIViewContentModeScaleAspectFill;
UILabel *cellLabel = (UILabel *)[newCell viewWithTag:klabelTag];
// assigning value to cell label and image view
NSString *productImageLocalPath = aProduct.imageLocalPath;
if ([[NSFileManager defaultManager] fileExistsAtPath:productImageLocalPath]) {
// file exists at local path :-)
// means less fun :-(
cellImageView.image = [UIImage imageWithContentsOfFile:productImageLocalPath];
}
else
{
UIActivityIndicatorView *downloadActivityIndicator = (UIActivityIndicatorView *)[newCell viewWithTag:kActivityIndicator];
downloadActivityIndicator.hidden = NO;
[downloadActivityIndicator startAnimating];
// file does not exist at local path :-(
// means more fun :-)
[self.sessionController setupAndStartDownloadTaskForProduct:aProduct withCompletionHandler:^(NSString * tempLocalPath){
// download was successful
NSData *imageData = [[NSData alloc] initWithContentsOfFile:tempLocalPath];
[imageData writeToFile:productImageLocalPath atomically:YES];
cellImageView.image = [UIImage imageWithData:imageData];
[downloadActivityIndicator stopAnimating];
} andFailureHandler:^{
cellImageView.image = nil;
[downloadActivityIndicator stopAnimating];
}];
}
// setting values
cellLabel.text = aProduct.imageName;
return newCell;
}
在会话控制器类中,我有以下方法来启动新的下载任务:
- (void)setupAndStartDownloadTaskForProduct:(Products *)aProduct withCompletionHandler:(DownloadedCompletionHandler)completionHandler andFailureHandler:(DownloadedFailureHandler)failureHandler
{
NSString *completeImagePath = [kBasePath stringByAppendingPathComponent:aProduct.imageRelativePath];
NSURL *downloadURL = [NSURL URLWithString:completeImagePath];
if (!self.session) {
[self setUpSession];
}
NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:downloadURL];
NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithRequest:downloadRequest];
NSDictionary *downloadInfoDict = @{kSuccessHandlerKey: [completionHandler copy], kFailureHandlerKey: [failureHandler copy]};
self.downloadTasks[@(downloadTask.taskIdentifier)] = downloadInfoDict;
// resuming the download task
[downloadTask resume];
}
在上面的方法中,我将successHandler和failureHandler块存储在字典中,使用其任务标识符将其映射到下载任务。
以下是didFinishDownloadingToURL方法的实现:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
dispatch_async(dispatch_get_main_queue(), ^{
// invoking success block
DownloadedCompletionHandler successCompletionHandler = self.downloadTasks[@(downloadTask.taskIdentifier)][kSuccessHandlerKey];
successCompletionHandler([location path]);
// removing download task key-value pair from dictionary
[self.downloadTasks removeObjectForKey:@(downloadTask.taskIdentifier)];
});
}
我的问题是 - 有时候在上面的方法中,downloadTask会返回一个与在setupAndStartDownloadTaskForProduct中启动的标识符不同的标识符,因为获取的successCompletionHandler为nil,当我尝试调用处理程序块时app崩溃
现在我的问题是:
为什么在didFinishDownloadingToURL中我获得的标识符与在setupAndStartDownloadTaskForProduct处启动的标识符不同?
如果这是预期的行为,那么实施我的要求的最佳方式是什么?
答案 0 :(得分:0)
您正在使用的taskIdentifier显然是NSUInteger。你正在做的是使用NSNumber作为文字快捷键的键:
NSNumber * key = @(downloadTask.taskIdentifier);
问题是在词典中使用除NSString之外的任何东西都是个坏主意。您所做的是创建一个具有相同值的NSNumber对象,但不保证-isEqual:的计算结果为true。
不使用NSNumber密钥,而是将密钥转换为字符串:
NSString * key = [NSString stringWithFormat:@"%d", downloadTask.taskIdentifier];
然后字典哈希就可以了。
答案 1 :(得分:-1)