Bmacin
Bmacin

Reputation: 243

How to check if WKWebView URLAuthenticationChallenge is failed or succeeded?

I am using WKWebView to open a url but before that it authenticates the user. It is working fine when we input the correct credentials but in case of wrong credentials, I am unable to find any delegate or function that can detect the failure.

Code:

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)

    }

I can detect the previousFailureCount from URLAuthenticationChallenge, in case of failed response failureResponse always gives status code: 401. Any better way to detect the failure or success for URLAuthenticationChallenge?

Upvotes: 1

Views: 1563

Answers (1)

Rachit Agarwal
Rachit Agarwal

Reputation: 376

You can get status code from the response. Implement the delegate method

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

Upvotes: 0

Related Questions