我正在向UIWebView发送请求.加载的网页上有AJAX调用.我需要分析AJAX流量,以便在用户登录时确定.为此,我在AppDelegate中安装了一个NSURLCache:
MYURLCache *cache = [[MYURLCache alloc] init];
[NSURLCache setSharedURLCache:cache];
Run Code Online (Sandbox Code Playgroud)
此MYURLCache类正确接收通过webview运行的流量.我只能终止AJAX调用.然后我产生了一个自己的AJAX调用请求.这个返回来自网络服务器的完美回复.所以现在要做的最后一步是构建NSCachedURLResponse返回对象.我也管理过这个,但是webview在返回对象时什么都不做.如果我只返回nil,则WebView会加载所有内容(nil是NSURLCache的消息,没有任何内容被缓存,因此webview应该开始自行加载).
- (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] …Run Code Online (Sandbox Code Playgroud)