在iOS中使用Swift捕获Javascript事件

我使用networking编程语言构build应用程序,并希望在用户单击HTMLbutton时启动相机。 由于我希望我的相机视图是一个自定义的,我需要用Swift来devise它。 所以当用户点击这个HTMLbutton时,我想在Swift中“捕捉”这个点击,这样我就可以开始我的本地相机视图。

我知道这可以用WKWebview来完成,但是我真的不知道该怎么做。

例如,我的Javascript(jQuery)代码可能看起来像这样:

// User clicks to start the native camera with Swift $(".camera_button").click(function() { // Function to call the camera view from JS to Swift }); 

你能帮我做这个吗?

谢谢。

根据@Alex Pelletier的回答,这真的帮了我很大的忙,这里是我的问题的解决scheme。

在我的“loadView()”函数,这里是我有:

 let contentController = WKUserContentController(); contentController.addScriptMessageHandler( self, name: "callbackHandler" ) let config = WKWebViewConfiguration() config.userContentController = contentController webView = WKWebView(frame: CGRectZero, configuration: config) webView.navigationDelegate = self view = webView 

我的函数来处理发送给Swift的Javascript事件:

 func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if(message.name == "callbackHandler") { print("Launch my Native Camera") } } 

…最后,当我的相机button(HTML)发生点击时,我的Javascript(jQuery)代码:

 $(document).ready(function() { function callNativeApp () { try { webkit.messageHandlers.callbackHandler.postMessage("camera"); } catch(err) { console.log('The native context does not exist yet'); } } $(".menu-camera-icon").click(function() { callNativeApp(); }); }); 

我希望这会帮助别人:-)!

首先让我们创build一个js文件。 在js中,当你点击一个元素时,你可以像这样发送一个消息:

 varmessageToPost = {'ButtonId':'clickMeButton'}; window.webkit.messageHandlers.buttonClicked.postMessage(messageToPost); 

在创build了js文件和wkwebview后,您需要注入脚本:

  // Setup WKUserContentController instance for injecting user script var userController:WKUserContentController= WKUserContentController() // Get script that's to be injected into the document let js:String= GetScriptFromResources() // Specify when and where and what user script needs to be injected into the web document var userScript:WKUserScript = WKUserScript(source: js, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd forMainFrameOnly: false) // Add the user script to the WKUserContentController instance userController.addUserScript(userScript) // Configure the WKWebViewConfiguration instance with the WKUserContentController webCfg.userContentController= userController; //set the message handler userController.addScriptMessageHandler(self, name: "buttonClicked") 

最后你必须添加监听器function:

 func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let messageBody:NSDictionary= message.body as? NSDictionary{ // Do stuff with messageBody } } 

源代码