問題描述
與WindowsPhone不一樣,iOS UIWebView並不認爲403/404這種狀況下頁面訪問是失敗的,這也情有可原,但有時候,咱們須要對WebView所遇到的403/404進行處理。html
解決思路
因爲WebView在回調事件,要麼發生在NSURLConnection請求以前:python
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;web
- (void)webViewDidStartLoad:(UIWebView *)webView;ide
要麼發生在NSURLConnection請求以後:spa
- (void)webViewDidFinishLoad:(UIWebView *)webView;.net
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;rest
這兩種狀況下都沒法獲取狀態碼,故NSURLConnection必須由咱們來完成。而後讓WebView調用loadData方式展示頁面,而403/403由咱們本身處理。code
解決方案
-
-
- - (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;
- }