swift 3 - WKWebView 中的 http 身份验证

swift 3 - http authentication in WKWebView

我正在尝试构建一个显示网页的简单 WebView - 该页面需要对所有页面进行 http 身份验证(用于测试目的)。

这是我的代码:

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

}

我找到了 willSendRequestForAuthenticationChallenge 和 didReceiveAuthenticationChallenge,但是调用了其中的 none 并且我从服务器收到错误消息说我没有通过身份验证。

有人可以帮忙吗?

非常感谢!

大卫

通过添加“_”修复了变体 #1:

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

它通过删除(或注释掉)这一行来工作。 challenge.sender?.use(credential, for: challenge) 我也在其他 iOS 版本 9.X、10.1、10.2 和 10.3 中检查过它。 一切正常。

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)
    completionHandler(URLSession.AuthChallengeDisposition.useCredential, credential)

}