1

我需要缓存进入 web 视图的 web 来源图像(即不是捆绑来源)。通常我只是请求图像并将其转换为 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.");
 }

}
4

0 回答 0