直接上代码
- (void)webViewDidFinishLoad:(UIWebView *)webView {
// 404拦截处理,当后台配有404页面时,可能会出现404展示到一半,然后直接隐藏后,显示空白处理的效果,产品接受此处理
NSCachedURLResponse *resp = [[NSURLCache sharedURLCache] cachedResponseForRequest:webView.request];
if ([resp.response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)resp.response;
NSInteger statusCode = [httpResponse statusCode];
if (statusCode == 404) {
[self hideNetworkErrorTipView];
self.title = @"";
self.webView.hidden = YES;
[self.view showNoDataTipViewWithText:@"找不到指定的页面" imageString:@"search"];
return;
}
}
}
揣测:
当webview加载的时候,会暂时缓存请求(如果没有特别指定千万别缓存的情况下),所以通过[NSURLCache sharedURLCache]的方式能够拿到缓存的response,至于为什么能够强制转换NSURLResponse为NSHTTPURLResponse,是因为我们走的http请求,最终实例是一个NSHTTPURLResponse。
NSHTTPURLResponse的类说明
An NSHTTPURLResponse object represents a response to an
HTTP URL load. It is a specialization of NSURLResponse which
provides conveniences for accessing information specific to HTTP
protocol responses.