Dav*_*vid 2 http-authentication swift wkwebview swift3
我正在尝试构建一个显示网页的简单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)
}
}
Run Code Online (Sandbox Code Playgroud)
我找到了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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4825 次 |
| 最近记录: |