DEV Community

Akira Kashihara
Akira Kashihara

Posted on

How to Display a Web Application with Basic Authentication in WKWebView using SwiftUI (iOS)

This article shows how to display a web application with basic authentication in WKWebView using SwiftUI.

Source Code

This source code was made with reference to "WKWebView with Basic auth" and "Using WebKit Delegates".

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        WebViewTest()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Enter fullscreen mode Exit fullscreen mode

WebViewTest.swift

import SwiftUI
import WebKit

struct WebViewTest: UIViewRepresentable {
    func updateUIView(_ uiView: WKWebView, context: Context) {
        //
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    var url: String = "https://hogehoge.hoge"

    func makeUIView(context: Context) -> WKWebView {
        let view = WKWebView()
        view.navigationDelegate = context.coordinator
        view.load(URLRequest(url:URL(string: url)!))
        return view
    }

    class Coordinator: NSObject, WKNavigationDelegate {
            let parent: WebViewTest

            init(_ parent: WebViewTest) {
                self.parent = parent
            }

        func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge,
                         completionHandler: @escaping(URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
                let credential = URLCredential(user: "The user name to Basic Auth.",
                                               password: "The password to Basic Auth.",
                                               persistence: .forSession)
                completionHandler(.useCredential, credential)
            }
        }
}

struct WebViewTest_Previews: PreviewProvider {
    static var previews: some View {
        WebViewTest()
    }
}
Enter fullscreen mode Exit fullscreen mode

The Result

I cannot show you the contents of the web application. But I guess that you can check that all contents (text and images) are loaded.

WKWebView


This original article is the following that is written by me. This is a translation of a portion of this original article from Japanese to English.

Top comments (0)