In my iOS app, I would like to use a WKWebView to wrap an external URL in the application. This URL requires basic authentication (it needs user and password credential, lik
In a simpler way:
Though this answer looks redundant but posting as this may help other naive developers (like me).
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard (webView.url?.host) != nil else {
return
}
let authenticationMethod = challenge.protectionSpace.authenticationMethod
if authenticationMethod == NSURLAuthenticationMethodDefault || authenticationMethod == NSURLAuthenticationMethodHTTPBasic || authenticationMethod == NSURLAuthenticationMethodHTTPDigest {
let credential = URLCredential(user: userName, password: password, persistence: .none)
completionHandler(.useCredential, credential)
} else if authenticationMethod == NSURLAuthenticationMethodServerTrust {
completionHandler(.performDefaultHandling, nil)
} else {
completionHandler(.cancelAuthenticationChallenge, nil)
}
}