【发布时间】:2016-12-04 16:16:12
【问题描述】:
我正在尝试构建一个显示网页的简单 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,但它们都没有被调用,而且我从服务器收到错误,表明我没有通过身份验证。
有人可以帮忙吗?
非常感谢!
大卫
【问题讨论】:
-
通过添加“”修复变体 #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) }
-
您的意思是使用 WKUIDelegate 吗?我用 WKNavigationDelegate 扩展了我的视图控制器类(设置 webView.navigationDelegate = self 而不是 webView.uiDelegate = self)并实现了以下功能: func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition , URLCredential?) -> 无效) {
-
是的,我已经在下面分享了答案
-
有趣的是,直到我将 WKUIDelegate 更改为 WKNavigationDelegate 并将 webView.uiDelegate = self 更改为 webView.navigationDelegate = self 后,我的完成处理程序才被调用
标签: swift swift3 wkwebview http-authentication