ios - 仅当用户在 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,这是我不想要的。
任何帮助将非常感激。预先感谢。
解决方案
您可以评估证书的有效性,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
注意:无论如何你都必须打电话。
推荐阅读
- ecmascript-6 - lambda 表达式的返回值
- python - 使用 BeautifulSoup 从隐藏形式中获取价值
- javacc - 在 JavaCC 中使用 If 语句
- angular - formGroup Angular 2 如何调用方法验证?
- php - 一段时间后,我的购物车中的会话过期
- php - Laravel 多个属于用户
- flutter - Flutter 中有无模式对话框吗?
- r - 将两个元素列表合并为一个具有相同元素但每个元素有两个变量的列表
- javascript - 动态更改分配的点击功能
- ios - 崩溃的范围:com.apple.main-thread EXC_BREAKPOINT on ViewController Initialisation