1
我試圖緩存從Flickr加載的圖像。如果我加載相同的圖像,我希望使用緩存版本。出於某種原因,當我從互聯網下載圖像時,它可以正常工作,但是如果從緩存中加載它,則會顯示空白圖像。我檢查了cacheData,並且它與我放入的圖像具有相同的位數,所以看起來加載文件正在工作。緩存UIImage作爲NSData並讓它回來
這是我如何緩存圖片:
+ (void)cachePhoto:(NSData *)photo withKey:(NSString *)key {
if (photo) {
NSArray * urlArray = [fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSURL * targetDirectory = (NSURL *)[urlArray objectAtIndex:0];
targetDirectory = [targetDirectory URLByAppendingPathComponent:key];
[photo writeToURL:targetDirectory atomically:YES];
[cachedPhotos addObject:key];
NSLog(@"target url %@", targetDirectory);
}
}
+ (NSData *)photoInCache:(NSString *)key {
if ([cachedPhotos containsObject:key]) {
NSString * path = [[cacheDirectory URLByAppendingPathComponent:key] path];
NSLog(@"path: %@", path);
return [fileManager contentsAtPath:path];
} else {
return nil;
}
}
而且我的代碼把它找回來:
NSData * cacheData = [PhotoCache photoInCache:key];
if (cacheData) {
self.imageView.image = [UIImage imageWithData:cacheData];
[spinner stopAnimating];
NSLog(@"used cached image");
} else {
dispatch_queue_t downloadQueue = dispatch_queue_create("get photo from flickr", NULL);
dispatch_async(downloadQueue, ^{
NSData * imageData = [[NSData alloc] initWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
[spinner stopAnimating];
self.imageView.image = [UIImage imageWithData:imageData];
[PhotoCache cachePhoto:imageData
withKey:key];
});
});
}
NSData * thumbnailData = UIImagePNGRepresentation(thumbnailImage);試試這一行代碼。 –