Javascript and Swift

How to enhance your apps with scripting

Sergio Ordine
Academy@EldoradoCPS
2 min readNov 8, 2020

--

The iOS platform provides, since iOS7, the JavaScriptCore framework, a way to use the WebKit javascript engine embedded on our apps. You can use it independently of a web view, what makes it a useful component when you new to flexibilize a feature or set of features.

Note: All code presented here was run in a Swift Playground (XCode 12.1).

The Basics

Let's start with the basics given through the following code:

We need do import the JavaScriptCore framework in order to use it. This framework provides an environment, given by the class JSContext, that is to run the scripts (using the evaluateScript function).

The script is passed to the function as a regular String. So it can be defined on code, get from a file or even from internet (from a remote source as a server-side application).

The last result from the script is returned by evaluateScript as a JSValue (it is important to notice that it could be also an undefined value).

The JSValue provides a set of functions to convert a javascript value to a Swift/Objective-C value (toInt32, toString, toDate, toArray between others), as well as functions to check the type returned (isNumber, isInt32, isString, isNull, isUndefined etc.). Using this set of tools you can both check what was returned as well as unwrap this value to use it on your Swift code.

Passing Data Back and Forth

Is it possible also to store Swift values into javascript variables and get javascript variables values to use on Swift Code:

using the setObject function we can get a Swift value and store it as a JavaScript variable (named according the forKeyedSubscript parameter — notice that the name shall be casted as a NSString). This value can than be addressed as a javascript variable, as we can see on the evaluateScript.

On the opposite way, we can retrieve a javascript value (as a JSValue type) to use it on Swift using the objectForKeyedSubscript function.

Functions

In this article we check how to set the javascript environment, execute a script and pass from Swift to JavaScript and vice-versa. The next article will talk about how to bridge Swift functions to be used within javascript and also how to call javascript functions from Swift.

--

--

Sergio Ordine
Academy@EldoradoCPS

Software developer and educator. If you want to support me and my content production, please buy me a beer at https://www.buymeacoffee.com/sergioordine