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.

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: Stringfunc 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 = falsevar body: some View {Button("Terms & Conditions") {isTermsSheetPresented.toggle()}.sheet(isPresented: $isTermsSheetPresented) {HTMLView(fileName: "terms")}}

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips