问题
I'm trying to build a simple WebView which shows a web page - the page requires http authentication for all pages (for testing purposes).
Here is my code:
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)
}
}
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.
Could somebody help?
Thank you a lot!
David
回答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)
}
回答2:
It works by removing (or comment out) this line.
challenge.sender?.use(credential, for: challenge)
I have checked it also in other iOS versions 9.X, 10.1, 10.2 and 10.3.
It's working fine.
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)
}
来源:https://stackoverflow.com/questions/40960700/swift-3-http-authentication-in-wkwebview