swift 3 - WKWebView 中的 http 身份验证 [英] swift 3 - http authentication in WKWebView

查看:66
本文介绍了swift 3 - WKWebView 中的 http 身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to build a simple WebView which shows a web page - the page requires http authentication for all pages (for testing purposes).

这是我的代码:

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,但它们都没有被调用,而且我从服务器收到错误消息,我没有通过身份验证.

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.

有人可以帮忙吗?

非常感谢!

大卫

推荐答案

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

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

这篇关于swift 3 - WKWebView 中的 http 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆