Note that there are some explanatory texts on larger screens.

plurals
  1. POCacheing UIImage as NSData and getting it back
    primarykey
    data
    text
    <p>I'm trying to cache images I load from Flickr. If I load the same image, I'm hoping to use the cached version instead. For some reason, when I download an image from the internet, it works, but if I load it from my cache, it displays a blank image. I checked cacheData, and it has the same amount of bits as the image I put in, so it appears loading the file is working. </p> <p>Here is how I cache images:</p> <pre><code>+ (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; } } </code></pre> <p>And my code to get it back:</p> <pre><code>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]; }); }); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload