Add Swift WKWebView to Your App

Mazen Kilani
Swift2Go
Published in
2 min readApr 30, 2021

WKWebView Shows a Specified URL Website Page Content with a Loading Progress Bar Indicator.

Scenario

Our app will allow users to load and display content of a specific URL of a website page, abiding by Apple’s rules on unrestricted content.

Technique

Swift uses WebKit & WKWebView to load an external website page into your app. WKWebView has associated functions to ensure full implementation. You also need to utilise UIProgressView to monitor the website page load, so the user knows that the loading is actually happening (rather than a blank screen until website page fully loads).

However, to abide by Apple’s policies, the website page cannot be unrestricted or open to abuse. So, a decidePolicyFor method is implemented, which restricts the hosts (websites) that are allowed within the web view. This is usually your website (e.g., appsgym.com).

The best approach is to implement the whole WKWebView programmatically, without Storyboard @IBOutlets (as they are not needed if you are utilising the whole view).

Audience

The article is for Swift developers who seek complete, integrated, proven, code-centric solutions to speed up their development projects.

App Model

We based the article on the AppsGym Books model app, published on Apple’s App Store (as 8Books), and you can download the complete Xcode project on AppsGym.com, for free.

User Interfaces

SettingsTableViewController.swift displays a menu with the option to launch a Blog web page. The segue will launch the BlogViewController.swift that loads and displays the web page.

Logic

  • Assign variables webView and progressView
  • Set up progressView (a bar with a background color and progress color)
  • Add an observer to webView to monitor progress of loading the website page
  • Define website page URL to load
  • Implement the decidePolicyFor method, which specifies allowed websites
  • Monitor the page load progress, and reflect it on the progressView by expanding the progress color on the bar
  • Optionally, show a loading spinner when the page starts to load, and hide it once page is fully loaded

Code

The Swift code snippets below are extracts from BlogViewController.swift, which shows the AppsGym.com Blog page.

BlogViewController.swift viewDidLoad()

BlogViewController.swift WKWebView Methods

BlogViewController.swift extension

The article covered the complete code to load and display a specific URL website page (in our example, the Blog page), adhering to Apple’s guidelines and rules regarding the (un)restricted use of web links inside the app. Hope you find it useful. Thanks for reading!

--

--

Mazen Kilani
Swift2Go

I published 47 Swift iOS apps/games and 2 Flutter Android apps. I share complete Xcode projects, free (no ads), at AppsGym.com.