0

我正在使用 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,以防响应失败 failureResponse 总是给出状态码:401。有更好的方法来检测 URLAuthenticationChallenge 的失败或成功吗?

4

1 回答 1

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)
        }
    } 
}
于 2019-05-22T14:30:13.390 回答