Kimzi
Kimzi

Reputation: 31

WKWebView with Basic auth

I'm trying to create a simple app with a website embedded using WebView, everything works fine except that I don't understand how I would authenticate against a website that requires credentials. I've searched the web for several hours and finally given up on finding an answer. Might just be that I don't know what wording to use. Hope anyone on here knows a way either to hardcode the credentials or preferably a way for the user to enter their own credentials.

Thank you!

The code I'm using is the easiest possible, as follows:

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

Upvotes: 3

Views: 5080

Answers (2)

David Leppik
David Leppik

Reputation: 3304

The WKNavigationDelegate must be a class, not a struct. Override makeCoordinator() in UIViewRepresentable to bind the WKWebView to a WKNavigationDelegate. See this sample code.

Upvotes: 0

gi097
gi097

Reputation: 7703

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

Read more here:

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

Upvotes: 13

Related Questions