WKWebView加载需要登录密码的网页时,默认不实现弹出登录输入框
解决方法:设置代理,实现自定义认证
webView.navigationDelegate = self
...
// MARK: - WKNavigationDelegate
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let authenticationMethod = challenge.protectionSpace.authenticationMethod
switch authenticationMethod {
case NSURLAuthenticationMethodDefault, NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest:
let alertController = UIAlertController(title: "登录", message: "message", preferredStyle: .alert)
alertController.addTextField { (textField) in
textField.placeholder = "UserName"
textField.textContentType = .username
textField.returnKeyType = .next
}
alertController.addTextField { (textField) in
textField.placeholder = "Password"
textField.textContentType = .password
textField.isSecureTextEntry = true
textField.returnKeyType = .go
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
completionHandler(.cancelAuthenticationChallenge, nil)
}
let loginAction = UIAlertAction(title: "Login", style: .default) { (_) in
guard let username = alertController.textFields?.first?.text,
let password = alertController.textFields?.last?.text else {
return
}
let credential = URLCredential(user: username, password: password, persistence: .forSession)
completionHandler(.useCredential, credential)
}
alertController.addAction(cancelAction)
alertController.addAction(loginAction)
self.present(alertController, animated: true, completion: nil)
case NSURLAuthenticationMethodServerTrust:
completionHandler(.performDefaultHandling, nil)
default:
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
网友评论