This was a challenge for me to make Swift talk to JS or JS to Swift. I have been working on an iOS app for years. With so many years of practice, I think I am very good at a deep technical level. I have also done a lot of html and JS programming. What I know about JS is mainly based on what I need to do on my blog.
In my app updates, what I need to do is to provide some information to users about how to use the app. An HTML view is a good choice for this purpose. However, I encountered a challenge that some of the information HTML needs is actually available easily on the Swift side. How can I let JS make a request to Swift, and then Swift pass the requested information back to JS?
This is what I mean by a bridge between Swift and JS.
Working Environment
In my project, I use a simple ViewController with a WKWebView UI component. The class is a very simple one. In the viewDidLoad event, an html file will be loaded into WKWebView. The content defined in the html file will be displayed on the view screen.
- class MyWebViewController: UIViewController
- {
- @IBOutlet weak var webView: WKWebView!
- {
- didSet {
- setup() // Place 1: magic will be injected from here.
- }
- }
- var htmlUrl: URL? = nil
- override func viewDidLoad()
- {
- super.viewDidLoad()
- guard let url = htmlUrl else { return }
- webView.loadFileURL(
- url
- allowingReadAccessTo: url)
- let request = URLRequest(url: url)
- webView.load(request)
- }
- override func viewWillDisappear(_ animated: Bool)
- {
- super.viewWillDisappear(animated)
- // Place 2: some codes to be added here.
- }
- }
My html file contains information about how JS is loaded. Normally, a JS script file is defined in the head section. For example,
- <head>
- <meta charset='UTF-8'/>
- <!-- JS functions used in html -->
- <script type="text/javascript" src="../myScriptFile.js"></script>
- ...
- </head>
As you can see from the above structure, I have a view controller with a web viewer, in Swift code to present html content. The JS files which will be referenced from html are in my project bundle. This is my working environment.
A Case Study
Here is my case. In my html content, there is one element for displaying my app version.
<h2 class="center">Version <span id="appVersion">to be filed</span></h2>
This could be easily done by using a JS function like this:
- function swift2JSCallFor(appVersion) {
- let e = document.getElementById("appVersion");
- e.innerHTML = appVersion;
- }
The version string can be easily obtained in Swift code. How can I make a call from Swift to this JS function with version information?
WKScriptMessageHandler
as a Gateway
Fortunately, Apple provides an API for the case of my view controller with WKWebView. WKScriptMessageHandler
is the name of this API. This handler protocol can be implemented as a message channel gateway between Swift and JS.
This gateway could be implemented in my view controller class. There are some codes required to set it up. The disadvantage of doing this in my view controller is that I would have to repeat a block of similar code again and again in other view controller classes if I needed to do a similar thing. Another point is that adding some codes just for this kind of gateway would pollute my view controller class and make it harder to read and maintain.
Build My Gateway Class
After my thorough study and tests of this framework and a good understanding of what is required, I decided to create a new class to encapsulate the business logic or structure outline inside my class and expose the necessary settings for customizing.
- import WebKit
- typealias ScriptMessageHandlerBlock =
- ((WKUserContentController,
- WKScriptMessage) -> ())
- class MyWKScriptBridgeHelper: NSObject
- {
- init(
- observer: String,
- scriptMessageHandlerBlock: ScriptMessageHandlerBlock?
- )
- {
- webObserver = observer
- wKScriptMessageHandlerBlock = scriptMessageHandlerBlock
- }
- private var webObserver: String = ""
- private var wKScriptMessageHandlerBlock:
- ScriptMessageHandlerBlock? = nil
- var webObserverName: String {
- return webObserver
- }
- }
- extension WKScriptMessageHandler: WKScriptMessageHandler
- {
- func userContentController(
- _ userContentController: WKUserContentController,
- didReceive message: WKScriptMessage)
- {
- guard let block = wKScriptMessageHandlerBlock else
- {
- return
- }
- block(userContentController, message)
- }
- }
The class logic is simple. Only two parameters are required to create an instance of this class. One is a webObserver name, which will be called from JS to Swift to the gateway implemented in this class. Another one is a block of code where Swift information will be gethered or prepared and JS functions will be called.
Set it up on the Swift Side
OK, so far so good. It is time to put it all together in practice!
In my view controller class, there are two places where I will put some code. The first place is to set up my gateway instance of the MyWKScriptBridgeHelper
class.
- class MyViewController
- {
- private var scriptHelper: MyWKScriptBridgeHelper!
- ...
- private func setup()
- {
- let webObserver = "appVersion"
- let block: ScriptMessageHandlerBlock
- = {
- [weak self] (userController, message) in
- guard let this = self else {
- return
- }
- // Make sure that it is html js function callback
- guard message.name ==
- webObserver else {
- return
- }
- // get app version string
- let v = ... // get app version
- let jsFunc = String(
- format: "swift2JSCallFor('%@')",
- v)
- // Sends back app version to hml js function
- this.webView.evaluateJavaScript(
- jsFunc,
- completionHandler: nil)
- }
- scriptHelper = MyWKScriptBridgeHelper(
- observer: webObserver,
- scriptMessageHandlerBlock: block)
- }
- ...
- }
In this setup(), two parameters are prepared for creating the instance of MyWKScriptBridgeHelper
. One is the name of "webObserver"
as the message name of the gateway. Another one is the block to verify the right message is received, to prepare the app version, and finally call a JS function "swift2JSCallFor()"
to send the app version to the JS side.
The second location is in the view controller disappear event, where you should perform some cleaning by removing any message handlers and deallocating scriptHelper
to avoid memory leaks.
- override func viewWillDisappear(_ animated: Bool)
- {
- super.viewWillDisappear(animated)
- guard let sh = scriptHelper else { return }
- // Clear message handler from script helper
- webView.configuration.userContentController.removeScriptMessageHandler(
- forName: sh.webObserverName)
- scriptHelper = nil
- }
That's all I need to do to set my gateway up. First, the gateway will handle a message requesting the app version from the JS side. Then it will call a JS function to pass the app version to JS.
HTML and JS Configuration
On the html and JS side, the first step is to make a request to Swift for the app version. This can be done by calling a JS function on html body element's onload attribute.
- <body onload="updateVersion()">
- ...
- <h2 class="center">Version
- <span id="appVersion">to be updated...</span></h2>
- ...
- </body>
The second step is to set up Javascript functions to make a request and to handle Swift calls.
- function updateVersion()
- {
- try {
- var msg = {}; // for empty parameter, it has to be {}
- // "appVersion" is the request message name on Swift side
- window.webkit.messageHandlers.appVersion.postMessage(msg);
- } catch(err) {}
- }
- // function to be called from Swift to pass app version
- // to JS.
- function swift2JSCallFor(appVersion) {
- let e = document.getElementById("appVersion");
- e.innerHTML = appVersion;
- }
The comment description in the Javascript explains everything. That's all. With the above configuration, Swift and JS can talk to each other and pass the required information as needed.
Here is a snapshot of my html view with the correct version updated. I am so happy that this update will be automatically done and I don't need to touch the html file in future updates.
I have a short summary at the conclusion of this blog. Swift-JS communication was new to me. I spent more than one week investigating and doing my tests. The above strategy is based on other resources (see references) and my effort. This is not the best and complete solution. I may miss something. Please leave comments and provide your better solutions. Critics are welcome.
References
- Blog: Web to native code communication on iOS using WKScriptMessageHandler
- Blog: Using WebKit to call WKWebView JavaScript from Swift and Swift from JavaScript
- SO: My comments on this SO question
- You may love my creative iOS app. Record your life notes just by tapping your mobile device. Keep your memory fresh when you review those taps with the time, location, and notes you add: TapMyNotes app
- My work tool is Xcode ver 13.4 and Swift ver 5.
0 comments:
Post a Comment