iOS UIWebView獲取403/404
阿新 • • 發佈:2019-02-19
問題描述
與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 for404
- return NO;
- } elseif (response.statusCode == 403) {
- // code for403
- return NO;
- }
- [webView loadData:data MIMEType:@"text/html" textEncodingName:nil baseURL:[request URL]];
- isRequestWeb = NO;
- return NO;
- }
- return YES;
- }