iOS-webView请求失败后处理

由于iOS的webView对于400、404等错误不算做请求失败,加载失败后是失败界面,这样会很不好看, 所以我们需要手动拦截请求返回的错误码,来添加加载失败的界面。

//webView的回调方法中实现
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSHTTPURLResponse *response = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
    if (response.statusCode == 200) {
        self.noMessageLabel.hidden = YES;
        return YES;
    }
    self.noMessageLabel.hidden = NO;
    return NO;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
     self.noMessageLabel.hidden = NO;
}

//刷新、重载
- (void)refreshBtnClick
{
    self.url = _url;
}

- (NOMessageView *)noMessageLabel{
    
    if (!_noMessageLabel) {
        _noMessageLabel = [[NOMessageView alloc] initWithFrame:CGRectMake(0, (webView.height - 200) / 2, kW, 200)];
        _noMessageLabel.imageView.image = CommomImage(@"no_network_icon");
        _noMessageLabel.messageLabel.text = @"网络异常,刷新试试";
        [_noMessageLabel.refreshBtn addTarget:self action:@selector(refreshBtnClick) forControlEvents:UIControlEventTouchUpInside];
        _noMessageLabel.refreshBtn.hidden = NO;
        [webView addSubview:_noMessageLabel];
        [webView bringSubviewToFront:self.noMessageLabel];
    }
    return _noMessageLabel;
}

你可能感兴趣的:(iOS-webView请求失败后处理)