Running JavaScript code inside a Swift app

It’s not a secret that my two favourite languages are Swift and JavaScript. I build iOS apps with Swift and use JavaScript on the web. They can be also used together to make an iOS app and to get some nice benefits.

The first phase in my projects is quite often to create a Minimum Viable Product. If the project includes developing both the web and iOS apps I explore the possibility to share the code base between these apps. Sharing part of the code base may cut down the development time simply because there are less lines to code in. The same functionality is implemented only once, which also decreases the amount of testing. Shared code base also helps to maintain the project in the long run.

Communication with 3rd party APIs was a key functionality on my recent project. I estimated that I could share a large chunk of code between iOS and web apps, so I wrote the API methods in JavaScript. 99% of that JavaScript was shared and only 1% was platform specific.

How to run Javascript in iOS app?

There are two ways to run JavaScript inside an iOS app. You can use JavaScripCore or WKWebView. WKWebView is more limited and it can run only JavaScript strings. It was enough for me in the MVP phase, so here’s the general approach how I started using JavaScript inside a Swift app.

WKScriptMessageHandler provides a way for a JavaScript function to send a message back to the Swift side. It is really easy. Just construct the message first and call the webkit message handlers.

– Moi moi! (a way of saying ‘see you!’ in Finnish)