ios wkwebview didReceiveAuthenticationChallenge crash解决
时间: 2023-12-10 18:37:18 浏览: 188
在 iOS 的 WKWebView 中,当出现 https 认证时,会触发 `didReceiveAuthenticationChallenge` 方法,但有时候会因为证书异常等原因导致程序崩溃。
解决方法如下:
1.在 `Info.plist` 文件中添加如下代码,允许所有的 https 请求:
```xml
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
```
2.在 `didReceiveAuthenticationChallenge` 方法中添加对证书的判断:
```swift
func webView(_ webView: WKWebView, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let host = webView.url?.host ?? ""
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust && challenge.protectionSpace.host == host {
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, credential)
} else {
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
```
这样就可以避免因为证书异常导致的程序崩溃了。
阅读全文