ios webview 拦截404

直接上代码

- (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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容