iOS UIWebView获取403/404
2013-12-21 12:39 三戒1993 阅读(100) 评论(0) 编辑 收藏 举报问题描述
与WindowsPhone不同,iOS UIWebView并不认为403/404这种情况下页面访问是失败的,这也情有可原,但有时候,我们需要对WebView所遇到的403/404进行处理。
解决思路
由于WebView在回调事件,要么发生在NSURLConnection请求之前:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
- (void)webViewDidStartLoad:(UIWebView *)webView;
要么发生在NSURLConnection请求之后:
- (void)webViewDidFinishLoad:(UIWebView *)webView;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
这两种情况下都无法获取状态码,故NSURLConnection必须由我们来完成。然后让WebView调用loadData方式展现页面,而403/403由我们自己处理。
解决方案
- #pragma mark -
- #pragma mark - UIWebView Delegate Methods
- - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
- {
- static BOOL isRequestWeb = YES;
- if (isRequestWeb) {
- NSHTTPURLResponse *response = nil;
- NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
- if (response.statusCode == 404) {
- // code for 404
- return NO;
- } else if (response.statusCode == 403) {
- // code for 403
- return NO;
- }
- [webView loadData:data MIMEType:@"text/html" textEncodingName:nil baseURL:[request URL]];
- isRequestWeb = NO;
- return NO;
- }
- return YES;
- }