将UIImage缓存为NSData并将其恢复

时间:2012-05-15 04:37:49

标签: objective-c ios5 uiimage nsdata

我正在尝试缓存从Flickr加载的图像。如果我加载相同的图像,我希望改为使用缓存版本。出于某种原因,当我从互联网上下载图像时,它可以工作,但如果我从缓存中加载它,它会显示一个空白图像。我检查了cacheData,它与我放入的图像具有相同的位数,因此显示加载文件正在工作。

以下是我如何缓存图片:

+ (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];
        });
    });
}

1 个答案:

答案 0 :(得分:0)

我想通了 - 我正在将图像加载到我的prepareForSegue中的imageView中,ImageView尚未加载。我在viewDidLoad中加载了图像并且它工作正常。我也不得不使用UIImagePNGRepresentation,就像评论中所建议的那样。