[iOS开发]WKWebView加载不受信任的https

由于在项目中展示https网页的时候,WKWebView中某些网址打不开(不显示),用谷歌浏览器打开发现是:服务器证书无效,其实就是网站不受信任。

1、 配置info.pist

首先确定 App Transport Security Settings是否添加,App Transport Security Settings下添加Allow Arbitrary Loads in Web Content为YES
假如App Transport Security Settings添加了,有设置NSAllowsArbitraryLoads 为 YES,可不用设置Arbitrary Loads in Web Content为YES

注:NSAllowsArbitraryLoads 为 YES 或者 Arbitrary Loads in Web Content为YES 两个不能同时设置
在这里插入图片描述

2、在WKWebView的代理方法

swift 4.0

func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        // 判断服务器采用的验证方法
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            if challenge.previousFailureCount == 0 {
                // 如果没有错误的情况下 创建一个凭证,并使用证书
                let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
                completionHandler(.useCredential, credential)
            } else {
                // 验证失败,取消本次验证
                completionHandler(.cancelAuthenticationChallenge, nil)
            }
        } else {
            completionHandler(.cancelAuthenticationChallenge, nil)
        }
    }

实现代理

 		self.webView = WKWebView.init(frame: CGRect.zero, configuration: config);
 		self.view.addSubview(webView);
        webView.uiDelegate = self
        webView.navigationDelegate = self;

参考文章stackoverflow

附录:
有设置NSAllowsArbitraryLoads 为 YES,可不用设置Arbitrary Loads in Web Content为YES的理由

在这里插入图片描述

发布了121 篇原创文章 · 获赞 54 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/wm9028/article/details/103009376