Skip to content

Instantly share code, notes, and snippets.

@tonycn
Created July 23, 2014 05:02
Show Gist options
  • Save tonycn/462f8425ff0762828cbc to your computer and use it in GitHub Desktop.
Save tonycn/462f8425ff0762828cbc to your computer and use it in GitHub Desktop.
iOS webview cache
//
// WebViewImageCache.m
// DoubanShuo
//
// Created by Jianjun Wu on 7/1/11.
// Copyright 2011 Douban Inc. All rights reserved.
//
#import "WebViewImageCache.h"
#import "UserAppPreference.h"
@implementation WebViewImageCache
- (BOOL)isImageResource:(NSString *)resourceURL {
static NSArray *nonImgSuffies = nil;
static NSArray *imgSuffies = nil;
if (!nonImgSuffies) {
nonImgSuffies = [[NSArray arrayWithObjects:@".html", @".htm", @".js", @".css", nil] retain];
}
if (!imgSuffies) {
imgSuffies = [[NSArray arrayWithObjects:@".bmp", @".gif", @".jpe", @".jpeg", @".jpg",
@".ico", @".png", @".tif", @".tiff", nil] retain];
}
NSString *nonImgSuffix = nil;
for (nonImgSuffix in nonImgSuffies) {
if ([resourceURL hasSuffix:nonImgSuffix]) {
return NO;
}
}
NSString *imgSuffix = nil;
for (imgSuffix in imgSuffies) {
if ([resourceURL hasSuffix:imgSuffix]) {
return YES;
}
}
return NO;
}
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
NSString *ua = [[request allHTTPHeaderFields] objectForKey:@"User-Agent"];
if ([UserAppPreference sharedInstance].browserNoPictureMode
&& ua && [ua rangeOfString:@"AppleWebKit"].length > 0) {
NSString *relativePath = [[request URL] relativePath];
UIImage *defaultImg = [UIImage imageNamed:@"place_webimageholder.png"];
NSData *imageData = UIImagePNGRepresentation(defaultImg);
if ([self isImageResource:relativePath]) {
//NSLog(@"return cached picture with data length: %d", [imageData length]);
NSURLResponse *response = [[[NSURLResponse alloc] initWithURL:[request URL]
MIMEType:@"image/png"
expectedContentLength:[imageData length]
textEncodingName:nil]
autorelease];
return [[[NSCachedURLResponse alloc] initWithResponse:response data:imageData] autorelease];
}
}
return [super cachedResponseForRequest:request];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment