我想从将 device id
返回给脚本的 java 脚本代码中调用一个 swift 函数,我已经添加了当前使用的代码。请告知如何从 swift 函数将值返回给 java 脚本
,在此先感谢
代码片段:
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)
}
最佳答案
尝试查看 WKWebView
上的 evaluateJavaScript(_:, completionHandler:)
函数,如 here 所述
要使用它,您的 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)
}
您还可以从 DeviceInfo
函数返回 javaScriptString
,然后在您的 userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
中调用它,重要的是:
- 您需要定义要执行的整个 JavaScript 字符串
- 你需要调用
evaluateJavaScript
希望对你有帮助。
关于javascript - 使用 wkwebview 从 javascript 调用返回值的 swift 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39632957/