問題描述
與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;}