我想从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)
}
答案 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)
中调用它,重要的是:
evaluateJavaScript
希望对你有所帮助。