Logo for tanaschita.com

How to present a local html file in SwiftUI

Learn how to use WKWebView with SwiftUI.

11 Sep 2023 · 3 min read

When developing iOS applications, we might need to show a locally stored html file to the user. We can implement that by using Apple's WebKit framework and its WKWebView class which allows us to incorporate web content into an iOS application.

Let's see how to do that.

Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

Since WKWebView is a UIView subclass, the first step is to create a UIKit view wrapper that we can use to integrate that view into our SwiftUI view hierarchy:

struct HTMLView: UIViewRepresentable {
let fileName: String
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ webView: WKWebView, context: Context) {
// TODO: Load HTML file contents into the web view.
}
}

With that in place, we can now create a resource URL and then use WKWebView's load(_ request: URLRequest) method to show it:

func updateUIView(_ webView: WKWebView, context: Context) {
guard let url = Bundle.main.url(forResource: fileName, withExtension: "html") else { return }
webView.load(URLRequest(url: url))
}

If we need to process or modify the html content programmatically before showing it, we could alternatively use the loadHTMLString(_ string: String, baseURL: URL?) method:

func updateUIView(_ webView: WKWebView, context: Context) {
guard let url = Bundle.main.url(forResource: fileName, withExtension: "html") else { return }
guard let htmlString = try? String(contentsOf: url, encoding: .utf8) else { return }
webView.loadHTMLString(htmlString, baseURL: url)
}

With that in place, we can now use it in a SwiftUI hierarchy, for example by embedding it in a sheet:

@State private var isTermsSheetPresented = false
var body: some View {
Button("Terms & Conditions") {
isTermsSheetPresented.toggle()
}.sheet(isPresented: $isTermsSheetPresented) {
HTMLView(fileName: "terms")
}
}
Sponsorship logo
Capture HTTP(s) traffic with Proxyman
Proxyman - Your ultimate man-in-the-middle proxy to effortlessly capture, inspect, and manipulate HTTP(s) traffic on macOS, Windows, iOS, and Android devices.
Get started for free

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

swiftui

swift

ios

How to implement pagination with SwiftUI's List view

Learn how to implement infinite scrolling with SwiftUI.

28 Aug 2023 · 4 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum