具有基本身份验证的 WKWebView

Kim*_*mzi 3 authentication ios wkwebview swift5 xcode11

我正在尝试创建一个简单的应用程序WebView,其中嵌入了使用的网站,一切正常,除了我不明白如何对需要凭据的网站进行身份验证。我在网上搜索了几个小时,最终放弃寻找答案。可能只是我不知道该用什么措辞。希望这里的任何人都知道一种对凭据进行硬编码的方法,或者最好是一种让用户输入自己的凭据的方法。

谢谢你!

我使用的代码是最简单的,如下所示:

import SwiftUI
import WebKit

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                WebView(request: URLRequest(url: URL(string: "https://siteurl")!))
            }.navigationBarTitle("Example Text")
        }
    }
}

struct WebView: UIViewRepresentable {
    let request: URLRequest

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.load(request)
    }
}
Run Code Online (Sandbox Code Playgroud)

Gio*_*gen 11

You can use the webView(_:didReceive:completionHandler:) callback from the WKNavigationDelegate. From there you can enter credentials and authenticate against the webpage.

You can implement it like the following (pseudo code):

struct WebView: UIViewRepresentable, WKNavigationDelegate {
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.navigationDelegate = self
        return webView
    }

    func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge,
                 completionHandler: @escaping(URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let credential = URLCredential(user: "username",
                                       password: "password",
                                       persistence: .forSession)
        completionHandler(.useCredential, credential)
    }
}
Run Code Online (Sandbox Code Playgroud)

Read more here:

https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455638-webview