JS在Swift中调用函数 [英] JS calling a function in Swift

查看:585
本文介绍了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.

这篇关于JS在Swift中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆