Swift:WKWebView 添加了像 Android 一样的 JavaScript 界面



我有一个页面,我想在包含动态内容的 Web 视图中显示该页面。

在Android上,我可以通过界面简单地做到这一点,这是界面:

class WebAppInterface (val context: Context, val userId: Long, val  type: String) {
    @JavascriptInterface
    fun getId(): Long {
        return userId
    }
    @JavascriptInterface
    fun getBaseUrl(): String{
       return Configuration.getInstance().userConfig.getStoredBaseUrl();
    }
    @JavascriptInterface
    fun getGetStatType(): String{
       return type;
    }
}

webview.addJavascriptInterface(WebAppInterface(this.applicationContext, id, statisticsType!! ), "android")

如何在iOS上做同样的事情,搜索后我得到了这个:

let contentController = WKUserContentController()
        contentController.add(self, name: "android") // -> Set a listener
        let config = WKWebViewConfiguration()
        config.userContentController = contentController
        let scriptString = "????? What write ir?"
        let script = WKUserScript(source: scriptString, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
        config.userContentController.addUserScript(script)
        webView = WKWebView(frame: .zero, configuration: config)

和委托方法:

 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print(message)
}

在委托方法中,当它到达关键字android时不会打印?为什么?我误解了操作吗?这是我的一些js代码,可以很好地与androidInterface配合使用

function getSteps() {
    const url = android.getBaseUrl() + 'patient/' + android.getId() + '/statistics/steps?from=' + from + '&to=' + to;
    Http.open("GET", url);
    Http.setRequestHeader('Authorization', 'Bearer ' + android.getToken())
    Http.send();
}

如何将值注入"android"js,就像我在Android上所做的那样。

我通过注入手动创建的 android 对象解决了这个问题,如下所示:

let scriptString = """
                       var android = {
                            getGetStatType: function() {
                                return 'sleep';
                            },
                            getId: function() {
                                return 98;
                            },
                            getBaseUrl: function() {
                                return 'baseUrl';
                            },
                            getToken: function() {
                                return 'myToken';
                            }
                       };
                       """
    let script = WKUserScript(source: scriptString, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true)
    config.userContentController.addUserScript(script)
不幸的是,

不可能从javascript同步调用swift方法来获取值。只有一种可能的方法是使用WKUserContentController的异步方式。在您的情况下,您很幸运,值不是动态的。例如,它不能用于获取一些随时间变化的值,例如GPS位置。

.SWIFT

webView.configuration.userContentController.add(self, name: "someName")
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print(message.name, message.body)
    webView.evaluateJavaScript("window.asyncResponseFromIos(123)")
}

.JS

window.webkit.messageHandlers.someName.postMessage("data")

因此,在Android和ios的JS中不可能有通用的同步接口。这就是为什么我要根据承诺制作JS接口的原因。在JS中,我将通过调用例如从android/ios获得价值 var value = await window.mobileAppInterface.get("someKey", "somePayload") 目标是在应用程序平台上拥有独立的通用JavaScript接口。