UIWebView加载Https网页报错

作者: 啃手高手 | 来源:发表于2016-07-21 21:49 被阅读5753次

ATS设置

按照惯例写一个UIWebView,用来加载网页:

_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
_webView.delegate = self;
[self.view addSubview:_webView];
NSURL *url = [NSURL URLWithString:@"https://github.com/"];
_request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:_request];

run一下看看加载出来了吗?如果发现屏幕一片白并没有出现网页内容,不要惊讶,看看你的控制台是不是报出以下错误:

NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)

这个怎么解决呢?没错ATS设置:去plist文件里添加一项App Transport Security Settings,它是个字典类型,给它增加一对键值,键:Allow Arbitrary Loads ,值设为YES。

以上,搞定ATS设置,网页成功加载了:

Simulator Screen Shot.png

如果你的网页是self signed website,那么你的屏幕应该还是一片白,并且控制台又报错:

NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)

注意:这两次错误并不是一样的,后面数字代码不同
(并不太清楚这个码代表的意思,有知道的朋友请留言告知,感谢。)

NSURLConnection

使用webview加载自签名https站点的时候,必须在请求的时候将该站点设置为安全的,才能继续访问。所以我们需要在webview开始加载网页的时候首先判断判断该站点是不是https站点,如果是的话,先让他暂停加载,用NSURLConnection 来访问改站点,然后再身份验证的时候,将该站点置为可信任站点。然后在用webview重新加载请求。

直接上代码:

#pragma mark - UIWebViewDelegate

// Note: This method is particularly important. As the server is using a self signed certificate,
// we cannot use just UIWebView - as it doesn't allow for using self-certs. Instead, we stop the
// request in this method below, create an NSURLConnection (which can allow self-certs via the delegate methods
// which UIWebView does not have), authenticate using NSURLConnection, then use another UIWebView to complete
// the loading and viewing of the page. See connection:didReceiveAuthenticationChallenge to see how this works.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
    NSLog(@"Did start loading: %@ auth:%d", [[request URL] absoluteString], _authenticated);

    if (!_authenticated) {

        _authenticated = NO;

        _urlConnection = [[NSURLConnection alloc] initWithRequest:_request delegate:self];

        [_urlConnection start];

        return NO;
    }
    return YES;
}

#pragma mark - NURLConnection delegate

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
    NSLog(@"WebController Got auth challange via NSURLConnection");

    if ([challenge previousFailureCount] == 0)
    {
        _authenticated = YES;

        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];

    } else
    {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

// 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
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

#pragma mark - NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
{
    NSLog(@"WebController received response via NSURLConnection");

    // remake a webview call now that authentication has passed ok.
    _authenticated = YES;
    [_web loadRequest:_request];

    // Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!)
    [_urlConnection cancel];
}

以上设置,可成功加载自签名网页。

但是,虽然加载成功,但是控制台还是报了以下错误:

NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9843)

最后

推荐参考链接:
stackoverflow Q1
stackoverflow Q2

相关文章

网友评论

  • 雷雨庭花:某些请求是受信任的,需要进行区分
  • lesmiserables0:方法不可行,估计是NURLConnection被弃用了。得研究NSURLSession 的方法了。
  • 西西西瓜sama:牛逼,感谢
    啃手高手:@西西西瓜sama :stuck_out_tongue::stuck_out_tongue:
  • 雷雨庭花:https请求了两次怎么解决啊
    羽纱:同样的问题
  • mysteryemm:按照楼主说的方法试了 还是不行
    lesmiserables0:我也是,现在解决了吗?
  • Python数据分析实战:2017元旦的时候要把ATS 强制改为NO ,然后怎么加载https不能加载网页
    liuyan3176:@Goyakod https://developer.apple.com/library/prerelease/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW59
    Python数据分析实战:@Goyakod 官方要求的强制改
    啃手高手:@SilenceYaung 还是要ats的。。。
  • 31e4be245ecf:GitHub有代码吗,请求一份参考
  • 厚脸皮小强打不死的小强:网页是self signed website
    啃手高手:@厚脸皮小强打不死的小强 嗯,对是自签名
  • 厚脸皮小强打不死的小强:当你发现,如果html里的图片链接跟html的域名不一样的时候,这样处理,图片还是加载不出来,研究好几天了
    背包客JW:这个问题最后解决了吗, 怎么解决的, 麻烦赐教:pray:
    liuyan3176:@厚脸皮小强打不死的小强 原来是这样,我说为什么在浏览器上把图片前缀加s也能展示,但是在app上就显示不了...
  • bigCatloveFish:如何用NSURLSession 去 处理这件事情呢?NSurlConnection 似乎 在iOS 7之后 就不建议使用了
    啃手高手:@bigCatloveFish :+1:
    bigCatloveFish:@Goyakod :joy:我写完了....
    啃手高手:@bigCatloveFish 好问题,研究下再来回复

本文标题:UIWebView加载Https网页报错

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