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
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值