IOS wkwebview 使用自签名证书

IOS wkwebview using self-assigned Cert

尝试使用 IOS 10 的自分配证书加载 HTTPS Url,但一直失败。

在此线程中发现类似问题,但解决方案不适用于更新版本的 Swift / SDK / IOS : Allow unverified ssl certificates in WKWebView

我不是在寻找对 App Store 有效的解决方案,只需要能够忽略 SSL 认证验证。

这是 ViewController.swift 文件:

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    var webView: WKWebView!

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self

        view = webView
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let url = URL(string: "https://X.X.X.X:XXXX")!
        //let url = URL(string: "https://google.com")!
        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge,
             completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let cred = URLCredential.init(trust: challenge.protectionSpace.serverTrust!)
        completionHandler(.useCredential, cred)
    }


}

您的委托方法签名不完全匹配。试试这个:

func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    let cred = URLCredential.init(trust: challenge.protectionSpace.serverTrust!)
    completionHandler(.useCredential, cred)
}