我需要缓存进入webview的网络源图像(即不是源代码包)。通常情况下,我只是请求图像并将其转换为base-64并将其粘贴到HTML中,但如果我有100个图像,我就不能那么做。
所以我搜索了一下,找到了通过继承NSURLCache
并覆盖cachedResponseForRequest
来获取图像请求的方法。我的代码如下。
我能够很好地完成请求,我可以将数据恢复并打印出来,我从数据中创建了一个UIImage并得到它的大小,知道它是definitely
等等。但是当我返回cachedResponseForRequest
本身,并查看UIWebView
时,它只会显示丢失的图像。我一直为此苦苦挣扎一天,无法弄明白。我看过例子之后的例子,没有雪茄。
任何人都可以帮我解决这个问题吗?这让我疯了......
以下是我的NSURLCache
子类的.m文件的内容。 GimageData
是用于存储接收的当前图像数据的实例变量。
就是你知道,为什么我搜索/替换http___到http://的原因是http://链接显然不会被这个方法拿起来,所以我让链接看起来像它的在捆绑中的东西然后我还原URL以供检索。
- (NSCachedURLResponse*)cachedResponseForRequest:(NSURLRequest*)request
{
NSURL *url = [request URL];
NSLog(@"Url requested is: %@", [url absoluteString] );
NSRange textRange;
textRange = [[[url absoluteString] lowercaseString] rangeOfString:[@"http___" lowercaseString]];
NSCachedURLResponse *cachedResponse = nil;
if(textRange.location != NSNotFound) {
//Does contain the substring
NSLog(@"Found an http___ request");
NSString *newURL = [[url absoluteString] substringFromIndex:textRange.location];
newURL = [newURL stringByReplacingOccurrencesOfString:@"http___" withString:@"http://"];
NSLog(@"New url: %@", newURL);
TTURLDataResponse *response = [[TTURLDataResponse alloc] init];
TTURLRequest *imageRequest = [[TTURLRequest alloc] initWithURL:newURL
delegate:self];
imageRequest.response = response;
[response release];
[imageRequest sendSynchronously];
if ( GimageData ) {
NSLog(@"Response: %d as %@", [GimageData bytes], [GimageData class]);
NSLog(@"Storing under: %@ ", request.URL );
NSURLResponse* Nresponse = [[NSURLResponse alloc] initWithURL:request.URL
MIMEType:nil
expectedContentLength:[GimageData length]
textEncodingName:nil];
cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:Nresponse
data:GimageData];
[imageRequest release];
[Nresponse release];
NSLog(@"Cached the response.");
}
}
if (cachedResponse == nil) {
NSLog(@"Response is nil so getting super's cache");
cachedResponse = [super cachedResponseForRequest:request];
}
return cachedResponse;
}
- (void)requestDidFinishLoad:(TTURLRequest*)request {
NSLog(@"Request did finish loading.");
TTURLDataResponse *response = request.response;
// NSURL *url = [NSURL URLWithString:request.urlPath];
GimageData = response.data;
if ( GimageData ) {
NSLog(@"And we got the data.");
}
else {
NSLog(@"But there was no data in the response.");
}
}