NSCachedURLResponse返回对象,但UIWebView不解释内容

我正在向UIWebView发送请求。 在加载的网页上有AJAX调用。 我需要分析的AJAXstream量,以确定,如果用户login或不。 为此,我在AppDelegate中安装了NSURLCache:

MYURLCache *cache = [[MYURLCache alloc] init]; [NSURLCache setSharedURLCache:cache]; 

这个MYURLCache类正确地接收通过webview运行的stream量。 我只能终止AJAX调用。 然后,我产生了一个AJAX调用自己的请求。 这个从web服务器返回完美的响应。 所以现在要做的最后一步是构造NSCachedURLResponse返回对象。 我也pipe理了这个,但是webview在返回对象的时候什么都不做。 如果我只返回零,WebView加载一切正常(零是NSURLCache的消息,没有任何caching,所以web视图应该开始加载它自己)。

 - (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request { if ([[[request URL] absoluteString] rangeOfString:@"/ajax/"].location == NSNotFound) { return nil; } else { ASIHTTPRequest *asirequest = [ASIHTTPRequest requestWithURL:[request URL]]; [asirequest setValidatesSecureCertificate:NO]; [asirequest startSynchronous]; NSError *error = [asirequest error]; NSData* data = [[asirequest responseString] dataUsingEncoding:NSUTF8StringEncoding]; // Create the cacheable response NSURLResponse *urlresponse = [[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"application/json" expectedContentLength:[data length] textEncodingName:@"UTF-8"]; NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:urlresponse data:data]; NSLog(@"cachedResponse %@", cachedResponse); NSLog(@"cachedResponse data %@", [[NSString alloc] initWithData:[cachedResponse data] encoding:NSUTF8StringEncoding]); return cachedResponse; } return nil; } 

我发现这个问题的一个解决scheme…我认为这是与丢失的标题有关。

如果我更换

 NSURLResponse *urlresponse = [[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"application/json" expectedContentLength:[data length] textEncodingName:@"UTF-8"]; NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:urlresponse data:data]; 

 NSHTTPURLResponse *urlresponse = [[NSHTTPURLResponse alloc] initWithURL:request.URL statusCode:200 HTTPVersion:@"1.1" headerFields:nil]; NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:urlresponse data:data]; 

整个事情的作品。 此答案另外build议请求的额外自定义标题。 https://stackoverflow.com/a/15234850/274518

 NSDictionary *headers = @{@"Access-Control-Allow-Origin" : @"*", @"Access-Control-Allow-Headers" : @"Content-Type"}; NSHTTPURLResponse *urlresponse = [[NSHTTPURLResponse alloc] initWithURL:request.URL statusCode:200 HTTPVersion:@"1.1" headerFields:headers]; 

在我的情况下,我不需要它。