首页 > 解决方案 > 仅当用户在 WKWebView 中同意时如何显示无效 SSL 证书警报并加载 URL

问题描述

嗨,我正在使用 WKWebView基于 Web 的浏览器,现在的问题是我想Alert在加载 URL 时显示一些内容,具有无效的 ssl 证书,如果用户仍想打开 URL,则只加载该 URL,否则会显示一些错误页面。

我知道如何使用以下WKWebView navigationDelegate方法绕过错误的 ssl 证书

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

但这会在不通知用户的情况下加载 URL,这是我不想要的。

任何帮助将非常感激。预先感谢。

标签: iosswiftsslwkwebview

解决方案


您可以评估证书的有效性,SecTrustEvaluateWithError然后检查错误,例如:

func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    var error: CFError?
    if let trust = challenge.protectionSpace.serverTrust, !SecTrustEvaluateWithError(trust, &error) {
        // OK
        let ok = UIAlertAction(title: "OK", style: .default) { _ in
            let exceptions = SecTrustCopyExceptions(trust)
            SecTrustSetExceptions(trust, exceptions)
            completionHandler(.useCredential, URLCredential(trust: trust))
        }
        
        // Cancel
        let cancel = UIAlertAction(title: "Cancel", style: .cancel) { _ in
            completionHandler(.cancelAuthenticationChallenge, nil)
        }
        
        // Show prompt
        let message = error!.localizedDescription + "\nDo you want to continue?"
        let alert = UIAlertController(title: "SSL Error", message: message, preferredStyle: .alert)
        alert.addAction(ok)
        alert.addAction(cancel)
        present(alert, animated: true, completion: nil)
    }
    else {
        completionHandler(.performDefaultHandling, nil)
    }
}

completionHandler注意:无论如何你都必须打电话。


推荐阅读