From time to time, operation team wants to change their content in real-time instead of waiting for new versions of iOS App updated. The two most common ways to fulfill their requirement are Remote Config and WKWebView. Cohering with the title, I’m only going to focus on WKWebView and demonstrate how we implement it.

Showing a web content

Let’s start from the very basic: showing a web content. Not much to explain.😗

Debugging with WKWebView

We can debug our iOS projects with the aid of Safari. Open Safari and press ⌘+, to open Preference, under the Advanced tab, check “Show Develop menu in menu bar”.

Not until we have the project build can we use the Safari debugger. The debugger is under Develop → Your simulator or device.

Modifying WebView with Javascript

Here I’ll create a button and a label with javascript, and also applies some CSS to it.

Debugging with Safari, I’ve found the desired <div id="main"> .

We can inject javascript code either using simple string or including it from a separate js file (script.js in my demo). Once we have the javascript code, we pass it to WKUserScript , and then wrap into WKUserContentController , then finally WKWebViewConfiguration for the initialization of WKWebView .

Listen to javascript events and respond back

We can listen to javascript events by adding scrip message handlers to WKUserContentController . and conforming WKScriptMessageHandler protocol.