Skip to content

Instantly share code, notes, and snippets.

@cloudwalking
Created October 16, 2014 16:57
Show Gist options
  • Save cloudwalking/74a364e168b641e44482 to your computer and use it in GitHub Desktop.
Save cloudwalking/74a364e168b641e44482 to your computer and use it in GitHub Desktop.
CachedImageView
#import "CachedImageView.h"
#import "Cache.h"
@implementation CachedImageView
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
self.contentMode = UIViewContentModeScaleAspectFill;
self.clipsToBounds = YES;
}
return self;
}
- (void)setImageURL:(NSURL *)imageURL {
_imageURL = imageURL;
if (_imageURL == nil) {
[super setImage:nil];
return;
}
NSData *data = [Cache objectForCacheKey:[_imageURL absoluteString]];
if (data) {
UIImage *image = [UIImage imageWithData:data];
[super setImage:image];
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSURLRequest *request = [NSURLRequest requestWithURL:_imageURL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error && [data length] > 0) {
[Cache cacheObject:data forKey:[_imageURL absoluteString]];
UIImage *image = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
[super setImage:image];
});
}
}];
[task resume];
});
}
- (void)reset {
self.image = nil;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment