美文网首页
WKWebView 实现登录认证(包含用户名密码输入框)

WKWebView 实现登录认证(包含用户名密码输入框)

作者: 七夕猪 | 来源:发表于2020-09-24 14:18 被阅读0次

    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)
        }
    }
    

    相关文章

      网友评论

          本文标题:WKWebView 实现登录认证(包含用户名密码输入框)

          本文链接:https://www.haomeiwen.com/subject/zfwzyktx.html