fra*_*ool 20 javascript jquery ios swift swift2
我正在使用Web编程语言构建应用程序,并希望在用户单击HTML按钮时启动相机.由于我希望我的相机视图是自定义的,我需要使用Swift进行设计.因此,当用户点击此HTML按钮时,我想在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
});
Run Code Online (Sandbox Code Playgroud)
你能帮帮我吗?
谢谢.
fra*_*ool 32
基于@Alex Pelletier的回答,这对我来说真的很有帮助,这就解决了我的问题.
在我的"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
Run Code Online (Sandbox Code Playgroud)
我的函数来处理发送到Swift的Javascript事件:
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
{
if(message.name == "callbackHandler") {
print("Launch my Native Camera")
}
}
Run Code Online (Sandbox Code Playgroud)
...最后,当我的相机按钮(在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();
});
});
Run Code Online (Sandbox Code Playgroud)
我希望它会帮助别人:-)!
Ale*_*ier 11
首先让我们创建一个js文件.在js中,当你单击一个元素时,你可以像这样发送一条消息:
varmessageToPost = {'ButtonId':'clickMeButton'};
window.webkit.messageHandlers.buttonClicked.postMessage(messageToPost);
Run Code Online (Sandbox Code Playgroud)
在创建了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")
Run Code Online (Sandbox Code Playgroud)
最后你必须添加监听器功能:
func userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage) {
if let messageBody:NSDictionary= message.body as? NSDictionary{
// Do stuff with messageBody
}
}
Run Code Online (Sandbox Code Playgroud)