Ios UIWebView 捕获404错误

404错误主要是指访问的页面不存在。原始页面的url失效,这种情况经常发生、很难避免。

在Ios使用UIWebView加载页面时,下面方法不能捕获该错误,给web开发带来很多不便。


- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error


UIWebView 404错误分两种情况,本地和远程。


注:以下代码都是添加到
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
方法中。


本地文件:

//是否是本地文件请求

    BOOL localRequest = NO;
    //请求url
    NSString *address = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if ([address hasPrefix:@"file:"])
    {
        localRequest = YES;
    }else
    {
        localRequest = NO;
    }
    
    NSFileManager *manager = [NSFileManager defaultManager];
    //如果是本地路径
    if (localRequest)
    {
        //请求的除@"file://"外的url
        NSString *resourceAddress = [[[request URL] resourceSpecifier] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //但是不存在该路径
        if (![manager fileExistsAtPath:resourceAddress])
        {
            return NO;
        }
	return YES;
    }



远程请求:


        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]];return NO;





链接:
http://stackoverflow.com/questions/4152759/uiwebview-didfailwitherror-is-not-responding-for-404-errors/14998144#14998144
http://www.cocoachina.com/bbs/read.php?tid=113029
http://blog.csdn.net/waterforest_pang/article/details/8599322

你可能感兴趣的:(ios,UIWebView,404)