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

我正在向UIWebView发送请求.加载的网页上有 AJAX调用.我需要分析 AJAX流量,以确定用户是否登录.为此,我在AppDelegate中安装了一个NSURLCache:
MYURLCache *cache = [[MYURLCache alloc] init];
[NSURLCache setSharedURLCache:cache];

此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] initWithData:[cachedResponse data] encoding:NSUTF8StringEncoding]);

    return cachedResponse;
}  

return nil;
}

解决方法

我找到了一个解决这个问题的方法……我认为这与丢失的标题有关.

如果我更换

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];

整件事情都有效.此答案另外建议了请求的附加自定义标头. 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];

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...