【发布时间】:2016-12-21 02:10:25
【问题描述】:
我已经看过几个关于这个问题的帖子,但我不知道如何让它发挥作用。比如这个帖子NSCachedURLResponse returns object, but UIWebView does not interprets content
建议我们在返回缓存响应之前继承并覆盖 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;
}
}
现在,当我通过 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];
这是我想要工作的流程:
- 启动应用程序。
- 点击一些网址(比如说 slickdeals.net)
- 脱机杀死应用程序
- 启动应用程序
-
UIWebView尝试点击 url 但设备处于离线状态并返回返回的缓存响应。 - 我们显示缓存的响应。
对我的代码需要更改的任何想法表示赞赏!
【问题讨论】:
标签: ios objective-c