如何使用wkwebview从swift返回boolean到javascript函数

时间:2017-12-08 08:19:00

标签: javascript ios swift wkwebview

这是我在android中的功能:

@JavascriptInterface
public boolean GetMobileVersion() {

    return true;
}

这是JavaScript中的调用函数:

$(window).load(function () {

    IsCallByMobileApp = false;
    try {
          IsCallByMobileApp = app.GetMobileVersion();/*Is call by android app*/

    } catch (e) {
        IsCallByMobileApp = false;
    }

}

在iOS中,我尝试使用WKWebView这样的方法来实现相同的方法,但它不起作用:

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

    if(message.name == callbackhandler) {

        webView.evaluateJavaScript("GetMobileVersion();")  { (true, error) in
            guard error == nil else {
                print("there was an error")
                return
            }

            print(Bool(true))
        }
    }
}

有谁能告诉我如何将true发送给Javascript函数?请给我详细解答,因为我是iOS和Swift的新手。

2 个答案:

答案 0 :(得分:1)

不确定WKWebView是否与webview相同,但您可以尝试使用以下明文:

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

if(message.name == callbackhandler) {

    webView.evaluateJavaScript("GetMobileVersion(true);")  { (true, error) in
        guard error == nil else {
            print("there was an error")
            return
        }

        print(Bool(true))
    }
}

}

答案 1 :(得分:1)

enter image description here 我为此创建了一个GitHub项目。 https://github.com/BKRApps/WKWebView-JS。请查看更多详情。

更新JavaScript:

 function getMobileVersion(){
        webkit.messageHandlers.VersionHandler.postMessage({})
    }

function receivedMobileVersion(mobileVersion){
        //here you will be getting the mobile version. Then execute the logic. 
        // i have added this only to cross check the version. you don't need to add this.

      if(mobileVersion === true) { 
      webkit.messageHandlers.VerifyHandler.postMessage({version:mobileVersion})
    }
 }

getMobileVersion()

将以下代码添加到WKWebView配置:

 configuration.userContentController.add(self, name: "VersionHandler")
// i have added this only to cross check the version. you don't need to add this.
 configuration.userContentController.add(self, name: "VerifyHandler")

更新WKScriptMessageHandler委托:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    switch message.name {
    case "VersionHandler":
        let mobileVersion = true //write the version logic and send the true or false.
        let sendMobileVersionScript = "receivedMobileVersion(\(mobileVersion))"
        self.wkWebView?.evaluateJavaScript("\(sendMobileVersionScript)", completionHandler: { (any, error) in
                            print("hello")
        })
    case "VerifyHandler":
        print(message.body) // i have added this only to cross check the version. you 
    default:
        break;
    }
}

了解更多信息:http://igomobile.de/2017/03/06/wkwebview-return-a-value-from-native-code-to-javascript/