我已经看到了这个问题的几个帖子,我无法弄清楚如何使这个问题。例如,这篇文章nscachedurlresponse返回对象,但UIWebView不解释内容
建议我们在返回缓存的响应之前将cachedResponseForRequest
子类和覆盖CC_1修改(不确定为什么需要这样做)。
这是我NSURLCache
子类中的代码:
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
NSCachedURLResponse *resp = [super cachedResponseForRequest:request];
if (resp != nil && resp.data.length > 0) {
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];
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:urlresponse data:resp.data];
return cachedResponse;
} else {
return nil;
}
}
现在,当我通过WebView加载请求并且我离线时,委托didFailLoadWithError
被调用(无法加载),但是在调用该委托方法之前,我的cachedResponseForRequest
方法被调用了,并且缓存的响应已被调用但是,一些HTML仍然调用我的didFailLoadWithError
方法。因此,我的问题是,如果我们从NSURLCache
返回缓存的响应,应该如何调用webViewDidFinishLoad
,如果不是,我该如何使此工作?
我在我的didFinishLaunchingWithOptions
中有这个:
NSUInteger cacheSizeMemory = 500*1024*1024; // 500 MB
NSUInteger cacheSizeDisk = 500*1024*1024; // 500 MB
NSURLCache *sharedCache = [[CustomCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];
这是我想要工作的流程:
- 启动应用程序。
- 点击一些URL(假设Slickdeals.net)
- 脱机杀死应用程序
- 启动应用程序
-
UIWebView
试图击中URL,但设备离线并返回缓存的响应。 - 我们显示缓存的响应。
对我的代码中需要更改的内容的任何想法都值得赞赏!
NSURLCache
是为HTTP符合缓存而设计的,并且经常表现不佳。您必须为您的用例编写自己的缓存,并实现自定义NSURLProtocol
以使用它。该协议将响应放入您的缓存中,并在离线时从缓存中提供它们。罗布·纳皮尔(Rob Napier)对此写了一篇出色的文章。