我想構建一個簡單的WebView,它顯示一個網頁 - 頁面需要所有頁面的http認證(用於測試目的)。swift 3 - WKWebView中的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 web視圖(_ web視圖: WKWebView,didReceive挑戰:URLAuthenticationChallenge,completionHandler:@escaping(URLSession.AuthChallengeDisposition,URLCredential?) - > Void){ let user =「user」 let password =「pass」 令憑證= URLCredential(用戶:用戶名,密碼:密碼,持久性:URLCredential.Persistence.forSession) challenge.sender。使用(證書號爲:挑戰)? completionHandler(URLSession.AuthChallengeDisposition.useCredential,證書) } – David
你的意思是使用WKUIDelegate嗎?我使用WKNavigationDelegate擴展了我的視圖控制器類(設置webView.navigationDelegate = self而不是webView.uiDelegate = self),並實現了以下功能:func webView(_ webView:WKWebView,didReceive challenge:URLAuthenticationChallenge,completionHandler:@escaping(URLSession.AuthChallengeDisposition ,URLCredential?) - > Void){ – CScott
是的,我分享了已經在 – David