Image 覆盖NSURLCache';s CachedResponseFor使用三个缓存UIWebView资产的请求20
我需要缓存要进入webview的web源映像(即非捆绑源映像)。通常我只需要请求图像并将其转换为base-64,然后将其粘贴到HTML中,但如果我有100个图像,我就无法做到这一点 因此,我四处搜索,找到了一种获取图像请求的方法,方法是通过子类化Image 覆盖NSURLCache';s CachedResponseFor使用三个缓存UIWebView资产的请求20,image,uiwebview,three20,nsurlcache,Image,Uiwebview,Three20,Nsurlcache,我需要缓存要进入webview的web源映像(即非捆绑源映像)。通常我只需要请求图像并将其转换为base-64,然后将其粘贴到HTML中,但如果我有100个图像,我就无法做到这一点 因此,我四处搜索,找到了一种获取图像请求的方法,方法是通过子类化NSURLCache并重写cachedResponseForRequest。我的代码如下 我可以很好地处理请求,我可以取回数据并将其打印出来,我从数据中制作了一个UIImage,并得到了它的大小,以知道它肯定在那里,等等。但是当我返回缓存响应请求本身,并
NSURLCache
并重写cachedResponseForRequest
。我的代码如下
我可以很好地处理请求,我可以取回数据并将其打印出来,我从数据中制作了一个UIImage,并得到了它的大小,以知道它肯定在那里,等等。但是当我返回缓存响应请求
本身,并查看UIWebView
,它只是显示了一个缺少的图像。我为这件事苦恼了一天,但还是想不出来。我看了一个又一个例子,没有雪茄
谁能帮我解决这个问题?它快把我逼疯了
下面是我的NSURLCache
子类的.m文件的内容GimageData
是一个实例变量,用于存储接收到的当前图像数据
正如你所知,我之所以搜索/替换http://to 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.");
}
}
事实上,如果确保同步发送请求,则可以将图像转换为base64并将其插入HTML。否则,图像将在加载HTML之后加载,您必须加载HTML两次。事实上,它可能是比拦截NSURLCache请求更优雅的解决方案。