DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. ๐Ÿ›