从使用wk webview返回值的java脚本调用swift函数

时间:2016-09-22 07:34:29

标签: javascript ios swift wkwebview wkwebviewconfiguration

我想从java脚本代码调用一个swift函数,它将device id返回给脚本,我添加了当前使用的代码。请告知如何从swift函数返回值java script,提前致谢

代码段:

     super.viewDidLoad()
    {
    self.webView = WKWebView()
    let preferences = WKPreferences()
    preferences.javaScriptEnabled = true
    let configuration = WKWebViewConfiguration()
    configuration.preferences = preferences
    configuration.userContentController = contentController
    configuration.userContentController.addScriptMessageHandler(self,name: "interOp")
    self.webView = WKWebView(frame: self.view.frame, configuration: configuration)
    print(self.view.frame)
    self.view = self.webView
    webView!.navigationDelegate = self
    let url = NSURL(string:"http://softence.com/devTest/vb_ios.html")
    let req = NSURLRequest(URL:url!)
    self.webView!.loadRequest(req)

    }

// did receivescript message is working fine
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
{
    let sentData = message.body as! NSDictionary
    print(sentData)
    if sentData["name"] as! String == "DeviceInfo"
    {
        self.DeviceInfo()
    }
}
// i want to return the following device info to javascript
func DeviceInfo() -> String
{
let dict = NSMutableDictionary()
    dict.setValue(UIDevice.currentDevice().model, forKey: "model")
    dict.setValue(UIDevice.currentDevice().name, forKey: "name")
    dict.setValue(UIDevice.currentDevice().systemVersion, forKey: "system_version")
    return String(dict)
}

1 个答案:

答案 0 :(得分:3)

按照here

的说明,试着查看evaluateJavaScript(_:, completionHandler:)上的WKWebView功能

要使用它,您的DeviceInfo函数应定义您要执行的完整JavaScript字符串

例如,如果你有一个像这样定义的JavaScript函数:

showDeviceInfo(model, name, system_version) {

}

然后你的DeviceInfo函数看起来像这样:

func deviceInfo() {
    let model = UIDevice.currentDevice().model
    let name = UIDevice.currentDevice().name
    let systemVersion = UIDevice.currentDevice().systemVersion

    let javaScriptString = "showDeviceInfo(\(model), \(name), \(systemVersion));" //string your JavaScript string together from the previous info...and no...it aint pretty :)
    webView.evaluateJavaScript(javaScriptString, completionHandler: nil)
}

您还可以从javaScriptString函数返回DeviceInfo,然后在userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)中调用它,重要的是:

  1. 您需要定义要执行的整个JavaScript字符串
  2. 您需要致电evaluateJavaScript
  3. 希望对你有所帮助。