Showing Local HTML Content in a WKWebView

Apple provides the WKWebView class to show web content in Swift apps. Most apps use web views to show content from websites, but you can also show local HTML in a web view. There are two common ways to show local HTML in a web view.

  • Loading HTML strings
  • Loading HTML files

Loading HTML Strings

The easiest way to display HTML content in a web view is to create a string for the HTML and call the loadHTMLString function.

A common reason to load an HTML string is to preview Markdown content. You can see examples of loading HTML strings in my WikiDemo and SwiftUIMarkdownEditor GitHub projects.

The biggest limitation of loading HTML strings and showing them in a web view is that images will not show. Inserting images in a HTML string is a security risk so the web view won’t display them.

Loading HTML Files

If you want to show images in a web view, you must create a HTML file and show it in the web view by calling the loadFileURL function. The function takes two arguments. The first argument is the URL of the file to show in the web view. The second argument is a URL that you give the web view access to read. You normally give read access to a folder that contains subfolders you want to show, such as image and CSS files.

I recently added code in an app to preview EPUB books in a web view. An EPUB book has an OEBPS folder that holds most of the book’s content. The OEBPS folder has the following subfolders:

  • A Text folder that contains the book’s chapters.
  • An Images folder that contains the book’s images.
  • A Styles folder that contains any CSS files to style the book.

To preview the book I needed to pass the URL of the current chapter’s HTML file as the first argument to loadFileURL and the URL of the OEBPS folder as the second argument. Giving the web view access to the OEBPS folder gives the web view access to the images and CSS files.