大佬教程收集整理的这篇文章主要介绍了ios – 在wkwebview中启用摄像头和麦克风访问,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我将此应用程序包装在WKWebView中,因为我想提供本机应用程序体验.我知道iOS不允许通过浏览器访问摄像头 – 但是有没有办法获得使用本机代码(与包装器一起)的网络摄像头/麦克风的权限并将其提供给Web应用程序 – 也许通过某种方式指向getUserMedia本地流源?
1.创建一个JavaScript文件(WebRTC.js),定义各种WebRTC类和函数,并将调用传递给WKWebView,例如:
(function() { if (!window.navigator) window.navigator = {}; window.navigator.getUserMedia = function() { webkit.messageHandlers.callBACkHandler.postmessage(arguments); } })();
2.在WKWebView中,在文档start处注入脚本:
let contentController = WKUserContentController(); contentController.add(self,name: "callBACkHandler") let script = try! String(contentsOf: Bundle.main.url(forresource: "WebRTC",withExtension: "js")!,encoding: String.Encoding.utf8) contentController.addUserScript(WKUserScript(source: script,injectionTime: WKUserScripTinjectionTime.atDocumentStart,forMainFrameOnly: truE)) let config = WKWebViewConfiguration() config.userContentController = contentController webView = WKWebView(frame: CGRect.zero,configuration: config)
3.侦听从JavaScript发送的消息:
class ViewController: UIViewController,WKUIDelegate,WKNavigationDelegate,WKScriptmessageHandler { var webView: WKWebView! func userContentController(_ userContentController: WKUserContentController,didReceive message: WKScriptmessagE) { if message.name == "callBACkHandler" { print(message.body) // make native calls to the WebRTC framework here } } }
4.如果需要在JavaScript-land中执行成功或失败回调,请直接在WKWebView中评估函数调用:
webView.evaluateJavaScript("callBACk({id: \(id),status: 'success',args: ...})",completionHandler: nil)
在调用postmessage之前,这些回调需要存储在JavaScript的哈希中,然后必须将哈希键发送到WKWebView.这是插件中的commandId.
int exec_id = 0; function exec(success,failure,...) { // store the callBACks for later if (typeof success == 'function' || typeof failure == 'function') { exec_id++; exec_callBACks[exec_id] = { success: success,failure: failure }; var commandId = exec_id; } webkit.messageHandlers.callBACkHandler.postmessage({id: commandId,args: ...}) } // the native code calls this directly with the same commandId,so the callBACks can be performed and released function callBACk(opts) { if (opts.status == "success") { if (typeof exec_callBACks[opts.id].success == 'function') exec_callBACks[opts.id].success(opts.args); } else { if (typeof exec_callBACks[opts.id].failure == 'function') exec_callBACks[opts.id].failure(opts.args); } // some WebRTC functions invoke the callBACks multiple times // the native Cordova plugin uses setKeepCallBACkAs(true) if (!opts.keepalivE) delete exec_callBACks[opts.id]; }
5.当然,将NSCameraUsageDescription和NSMicrophoneUsageDescription权限添加到项目的Info.plist中.
请记住,这是一项非常重要的任务,但这是使用异步回调桥接JavaScript,WKWebView和本机框架代码的总体思路.
以上是大佬教程为你收集整理的ios – 在wkwebview中启用摄像头和麦克风访问全部内容,希望文章能够帮你解决ios – 在wkwebview中启用摄像头和麦克风访问所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。