WKWebView中的用户名/密码身份验证

时间:2019-01-16 14:34:29

标签: ios swift authentication wkwebview

在Safari中访问网站时,它将询问用户名和密码。

出于某种原因,我试图将网站包装到应用程序中,但是无法启动用户名/密码提示。

这是我到目前为止的代码:

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
    var webView: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }

    func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let user = "*****"
        let password = "*****"
        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: "http://WebsiteName")!
        let myRequest = URLRequest(url: myURL)
        webView.load(myRequest)
    }
}

我希望会有一个用户名/登录提示框,但它只是一个401错误而没有提示。

1 个答案:

答案 0 :(得分:1)

几年前我对webView做过类似的事情,也许会有所帮助

webView.delegate = self
        guard let orderID = orderID else { return }
        let urlString = GET_PAYMENT_PAGE + "\(orderID)" + "&comments=" + DataManager.shared.peymentComment
        guard let url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!) else { return }
        var request = URLRequest(url: url)

        let username = Authentication.auth.phoneNumber
        let password = Authentication.auth.token
        let loginString = String(format: "%@:%@", username, password)
        let loginData = loginString.data(using: String.Encoding.utf8)!
        let base64LoginString = loginData.base64EncodedString()


        request.httpMethod = "POST"
        request.allHTTPHeaderFields = JSON_HEAD
        request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
        webView.loadRequest(request)