Skip to content

Instantly share code, notes, and snippets.

@mrtj
Created March 6, 2013 09:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrtj/5097996 to your computer and use it in GitHub Desktop.
Save mrtj/5097996 to your computer and use it in GitHub Desktop.
UIImageView category to download images asynchronously using the cache policy of the HTTP server if it is reachable otherwise look up for the image resource in the local HTTP cache. Depends on AFNetworking UIImageView category and Reachability components. #utils #image #UIImageView #cache #http #download
#import <UIKit/UIKit.h>
@interface UIImageView (OfflineCache)
-(void)setImageCachedWithURL:(NSURL*)url
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
@end
#import "UIImageView+OfflineCache.h"
#import "UIImageView+AFNetworking.h"
#import "Reachability.h"
@implementation UIImageView (OfflineCache)
-(void)setImageCachedWithURL:(NSURL*)url
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
NSURLRequestCachePolicy cachePolicy;
Reachability* currentReachability = [Reachability reachabilityForInternetConnection];
if (currentReachability.currentReachabilityStatus != NotReachable) {
cachePolicy = NSURLRequestUseProtocolCachePolicy;
} else {
cachePolicy = NSURLRequestReturnCacheDataDontLoad;
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:cachePolicy timeoutInterval:60];
[request setHTTPShouldHandleCookies:NO];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[self setImageWithURLRequest:request
placeholderImage:placeholderImage
success:success
failure:failure];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment