Skip to content

Customizable

iMoeNya edited this page Apr 23, 2024 · 1 revision

DSBridge-Swift has a Keystone that holds everything together.

A keystone is a stone at the top of an arch, which keeps the other stones in place by its weight and position. -- Collins Dictionary

Here is how a synchronous method call comes in and returns back:

Resolving Incoming Calls

The Keystone converts raw text into an Invocation. You can change how it resolves raw text by changing methodResolver or jsonSerializer of WebView.keystone.

import class DSBridge.Keystone
// ...
(webView.keystone as! Keystone).jsonSerializer = MyJSONSerializer()
// ...

There might be something you don't want in the built-in JSON serializer. For example it won't log details about an object or text in production environment. You can change this behavior by defining your own errors instead of using the ones defined in DSBridge.Error.JSON.

methodResolver is even easier. It simply reads a text and finds the namespace and method name:

(webView.keystone as! Keystone).methodResolver = MyMethodResolver()

Dispatching

After being resolved into an Invocation, the method call is sent to Dispather, where all the interfaces you added are registered and indexed.

You can, of course, replace the dispatcher. Then you would have to manage interfaces and dispatch calls to different interfaces in your own InvocationDispatching implementation.

(webView.keystone as! Keystone).invocationDispatcher = MyInvocationDispatcher()

JavaScript Evaluation

To explain to you how we can customize JavaScript evaluation, here's how an asynchronous invocation works.

Everything is the same before the invocation reaches the dispatcher. The dispatcher returns an empty response immediately after it gets the invocation, so that the webpage gets to continue running. From now on, the synchronous chain breaks.

Dispatcher sends the invocation to Interface at the same time. But since the way back no longer exists, DSBridge-Swift has to send the repsonse by evaluating JavaScript:

The JavaScriptEvaluator is in charge of all the messages towards JavaScript, including method calls initiated from native. The default evaluator evaluates JavaScript every 50ms to avoid getting dropped by iOS for evaluating too frequently.

If you need further optimization or you just want the vanilla experience instead, you can simply replace the Keystone.javaScriptEvaluator.

Keystone

As you can see from all above, the keystone is what holds everything together. You can even change the keystone, with either a Keystone subclass or a completely different KeystoneProtocol. Either way, you will be able to use DSBridge-Swift with any JavaScript.