我已经看到这个问题的几个职位,我不知道如何得到这个工作。例如,这篇文章NSCachedURLResponse returns object, but UIWebView does not interprets contentUIWebView NSURLCache加载离线数据
建议我们继承并覆盖cachedResponseForRequest
并在返回缓存响应之前修改NSURLRequest
(不知道为什么需要这样做)。
这是代码,我在我的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;
}
}
现在,当我加载通过web视图的要求,我下线,委托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,但设备处于脱机状态,并返回返回缓存的响应。- 我们显示缓存的响应。
任何想在我的代码中需要更改的想法是赞赏!