JS在Swift中调用函数

问题描述:

我知道如何从JS向本地IOS swift app发送消息:

I know how to send message from JS to native IOS swift app:

func userContentController(userContentController: WKUserContentController!, didReceiveScriptMessage message: WKScriptMessage!) {

        println("JavaScript is sending a message \(message.body)")

}

和JS:

webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");

我的问题:是否可以直接调用本机应用程序中的函数,而不是接收消息我的示例代码。

My question: is it possible to directly call a function in the native app rather then receiving the message in my example code.

我想在JS中使用类似的东西:

say i want in the JS to use something like:

webkit.messageHandlers.someFunctionName()

我问的原因是在Android中它是如何工作的

The reason i am asking is that In Android thats how it works

WKWebView仅支持原始消息传递接口。你必须将它包装在JS和native之间的复杂交互中。

WKWebView supports only the raw message passing interface. You have to wrap it for complex interactions between JS and native.

我创建了一个名为 XWebView ,它基于WKWebView的原始消息传递提供语言绑定样式的API。它是用Swift编写的。

I created a project named XWebView which offers language binding styled API based on the raw message passing of WKWebView. It's written in Swift.

例如,你可以在Swift中编写一个插件:

For example, you can write a plugin in Swift:

class Plugin : NSObject {
    func someFunctionName() {
        doSomeThing()
    }
}

在加载HTML之前将插件实例展示给JavaScript:

Expose an instance of the plugin to JavaScript before loading HTML:

let webView = WKWebView(frame: frame, configuration: WKWebViewConfiguration())
webView.loadPlugin(Plugin(), namespace: "foo")

从JavaScript调用函数:

Call the function from JavaScript:

window.foo.someFunctionName()

这真的很容易和直截了当。有关详细信息,请查看项目页面。

It's really easy and straightforward. For more details, please check the project's page.