2012-05-15 18 views
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]; 
     }); 
    }); 
} 
+2

NSData * thumbnailData = UIImagePNGRepresentation(thumbnailImage);試試這一行代碼。 –

回答

0

我想通了 - 我是加載圖像到我的prepareForSegue的ImageView的, ImageView尚未加載的位置。我加載了viewDidLoad中的圖像,它工作。我也必須使用UIImagePNGRepresentation,就像評論中所建議的那樣。