我正在使用WKWebView将React.js应用程序嵌入到本机iOS应用程序中。为了能够使用javascript处理本机功能,我按照本文https://medium.com/@JillevdWeerd/creating-links-between-wkwebview-and-native-code-8e998889b503的说明使用了WKScriptMessageHandler
,但是我的iOS应用不会收到任何消息。谁能告诉我原因?谢谢!
这是敏捷的一面:
override func loadView() {
super.loadView()
let contentController = WKUserContentController()
contentController.add(self as WKScriptMessageHandler, name: "PDFPrint")
let config = WKWebViewConfiguration()
config.userContentController = contentController
webView = WKWebView(frame: self.view.bounds, configuration: config)
webView.navigationDelegate = self
view = webView
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "PDFPrint", let messageBody = message.body as? String {
print(messageBody)
}
}
和javascript方面:
try {
webkit.messageHandlers.PDFPrint.postMessage('test message');
} catch(err) {
console.log('Can not reach native code');
}
如果需要,我可以提供整个ViewController.swift。