JS calling a function in Swift

本小妞迷上赌 提交于 2019-11-29 21:59:40

问题


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)")

}

and 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.

say i want in the JS to use something like:

webkit.messageHandlers.someFunctionName()

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


回答1:


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

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.

For example, you can write a plugin in Swift:

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

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

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

Call the function from JavaScript:

window.foo.someFunctionName()

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




回答2:


You could try to use URL query variables, like you would connect to PHP using Swift.

Here is an example of how to get query variables in Javascript: Get url parameter jquery Or How to Get Query String Values In js

Then when you run the Javascript you can check what the URL query variables are and then run a function based on that.

For example, we use the variable command below, to say what function to run:

example.com?command=foo

then do something like this in Javascript:

if(command == 'foo') {
   runFoo();
}

Then you could also use URL query variables to specify arguments for the function.

If you choose PHP

If you choose to use PHP, you can do the same thing with $_GET['command'];.



来源:https://stackoverflow.com/questions/30866155/js-calling-a-function-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!