Created
October 16, 2014 16:57
-
-
Save cloudwalking/74a364e168b641e44482 to your computer and use it in GitHub Desktop.
CachedImageView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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