Monday, March 4, 2024

Swift Rule Engine using Javascript for your iOS/MacOS application


This kind of workarounds are required when we want dynamic validation or to run some algorithm dynamically at runtime. We can download the business logic [as javascript text or file] from the server or can add to the bundle and can load and execute when it's needed.

In this way, we can keep the core business logic must be the same over multiple platform and can control without updating the application.

Form your app, you can pass values as parameters and the script can evaluate it and can return the result as plain text or JSON text if needed. 

First load the script using scripRunner.loadWebViewWithScript(script), and we can invoke a function using scripRunner.evaluateFunction(fnName: "function")


See the example code of passing a contact object to a script function and that function validate the contact object and returning a json object with true or false value.



The following  JavaScript handler file will help us to do the tasks easier.


As we are using async/await instead of completion handlers, we can evaluate a js function immediately after loading the html content. 
In this example, the loading of script content is done with onAppear and evaluating on the button click. In this way, we can do the load once and evaluate any times.