Swift:WKWebView需要身份验证。

时间:2017-02-22 10:56:22

标签: swift xcode wkwebview

我正在尝试将WKWebView添加到我的应用中。在文档之后,我实现了这个:

import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

    var webView: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let myURL = URL(string: "www.myurl.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
}

现在我的问题:我尝试访问的网站需要身份验证。在野生动物园我被要求。但我的应用程序只是提出错误" 404 - 这个网站不存在"。搜索后,我得到了接收URLAuthenticationChallenge可以解决问题的信息。通过互联网上的文档和信息,我添加了以下代码:

func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    print("test if pass")
    let user = "*****"
    let password = "*****"
    let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
    challenge.sender?.use(credential, for: challenge)
}

我添加了print语句,看看我是否进入了我的代码。但是在启动我的应用程序后仍然存在404错误,并且没有任何内容打印到我的控制台。

有人可以帮助我如何添加身份验证吗?谢谢:))

1 个答案:

答案 0 :(得分:2)

更新你的专栏,

let myURL = URL(string: "www.myurl.com")

let myURL = URL(string: "http://username:password@myURL.com/)

这有助于我解决与您相同的问题。希望这也对你有帮助。