【问题标题】:How to check if WKWebView URLAuthenticationChallenge is failed or succeeded?如何检查 WKWebView URLAuthenticationChallenge 是失败还是成功?
【发布时间】:2019-02-09 05:57:37
【问题描述】:

我正在使用 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 的失败或成功吗?

【问题讨论】:

    标签: ios swift wkwebview urlauthenticationchallenges


    【解决方案1】:

    您可以从响应中获取状态代码。实现委托方法

    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)
            }
        } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多