我正在使用WKWebView打开一个url,但在此之前它对用户进行身份验证。输入正确的凭据后,它可以正常工作,但是如果凭据输入错误,我将找不到任何可以检测到故障的委托或函数。
代码:
func webView(_ webView: WKWebView, didReceive challenge:
URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let user = "user"
let password = "password"
let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
completionHandler(URLSession.AuthChallengeDisposition.useCredential, credential)
}
在失败的响应失败的情况下,我可以从URLAuthenticationChallenge中检测到previousFailureCount。Response总是给出状态码:401。检测URLAuthenticationChallenge失败或成功的更好方法是什么?
答案 0 :(得分:0)
您可以从响应中获取状态代码。实现委托方法
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if let response = navigationResponse.response as? HTTPURLResponse {
if response.statusCode == 401 {
decisionHandler(.cancel)
} else {
decisionHandler(.allow)
}
}
}