美文网首页
UIWebView加载Https报错-1202

UIWebView加载Https报错-1202

作者: 君祁祁祁 | 来源:发表于2018-03-22 14:57 被阅读0次

把今天遇到的问题以及网上查找的方法结合一下,解决UIWebView加载https网站报错 “Error Domain=NSURLErrorDomain Code=-1202 ”的方法。

报错原因:主要是因为测试环境的证书是自签名的,所以存在这样的问题,而为什么有的https地址不会报错呢?这就要说到证书是否是通过CA证书中心发布的,如果是则不会,否则就会在第三次握手的时候不成功而报错。

解决方案:

NSAppTransportSecurity中 把NSAllowsArbitraryLoads 设置为YES,并不能解决问题。
//声明3个变量
NSURLConnection *_urlConnection; 
NSURLRequest *_request;
BOOL _authenticated;

//UIWebView代理方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *urlString = [NSString stringWithFormat:@"%@",request.URL];
//这里判断url地址是哪个
    if (!_authenticated && [urlString isEqualToString:@"************"]) {
        DT(@"_authenticated ");
        _authenticated =NO;
        _urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        _request = request;//request赋值
        [_urlConnection start];
        return NO;
    }
    return YES;
}


//NSURLConnectionDelegate 方法
#pragma mark - NURLConnection delegate

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    DT(@"didReceiveAuthenticationChallenge");
    if ([challenge previousFailureCount] == 0)
    {
        _authenticated = YES;
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
    } else
    {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    DT(@"didReceiveResponse");
    // remake a webview call now that authentication has passed ok.
    _authenticated = YES;
    [self.webView loadRequest:_request]; //  self.webView替换成自己的webview
    // Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!)
    [_urlConnection cancel];
}

// We use this method is to accept an untrusted site which unfortunately we need to do, as our PVM servers are self signed.
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    DT(@"canAuthenticateAgainstProtectionSpace");
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

希望这个解决方案对大家有用。

相关文章

网友评论

      本文标题:UIWebView加载Https报错-1202

      本文链接:https://www.haomeiwen.com/subject/ijonfftx.html