Du's Time

如何获取UIWebView请求时的HTTP状态码

Word count: 144 / Reading time: 1 min
2017/03/08 Share

有时我们需要向前端一样为请求错误的UIWebView界面添加更好看的本地错误提示,这就需要获取到UIWebView请求网页的HTTP状态码,基本思路是在webView请求结束后获取到缓存中的response,再根据response的statusCode进行判断,因此截获操作应该在UIWebViewDelegate中的webViewDidFinishLoad方法中进行

1
2
3
4
5
6
7
8
9
10
- (void)webViewDidFinishLoad:(UIWebView *)webView{
...
//获取status code
NSHTTPURLResponse *response = (NSHTTPURLResponse *)[[NSURLCache sharedURLCache] cachedResponseForRequest:webView.request].response;
NSInteger statusCode = response.statusCode;
if (statusCode == 404) { //或者换成你想要的其他状态码
//捕捉到404

}
...
CATALOG