I'm trying to build a simple WebView which shows a web page - the page requires http authentication for all pages (for testing purposes).
Here is my code:
class ViewController: UIViewController, WKUIDelegate {
    var webView: WKWebView!
    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }
    // #1 variant
    func webView(webView: WKWebView, willSendRequestForAuthenticationChallenge challenge:
        URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let user = "user"
        let password = "pass"
        let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
        challenge.sender?.use(credential, for: challenge)
    }
    // #2 variant
    func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
            let user = "user"
            let password = "pass"
            let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
            challenge.sender?.use(credential, for: challenge)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let myURL = URL(string: "https://myurl.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
}
I've found willSendRequestForAuthenticationChallenge and didReceiveAuthenticationChallenge, but none of them is called and I've got error from the server that I was not authenticated.
Could somebody help?
Thank you a lot!
David
Fixed variant #1 by adding "_":
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let user = "user"
        let password = "pass"
        let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
        challenge.sender?.use(credential, for: challenge)
        completionHandler(URLSession.AuthChallengeDisposition.useCredential, credential)
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With