您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在wkwebview中启用摄像头和麦克风访问

在wkwebview中启用摄像头和麦克风访问

是的,看看cordova-plugin-iosrtccordova-plugin-wkwebview- engine插件背后的想法如下:

创建一个定义各种WebRTC类和函数的JavaScript文件(WebRTC.js),并将调用传递给WKWebView,例如:

(function() {
  if (!window.navigator) window.navigator = {};
  window.navigator.getUserMedia = function() {
    webkit.messageHandlers.callbackHandler.postMessage(arguments);
  }
})();

在WKWebView中,在文档开始处插入脚本:

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)

收听从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
    }
  }
}

如果需要在JavaScript领域中执行成功或失败回调,请直接在WKWebView中评估函数调用

webView.evaluateJavaScript("callback({id: \(id), status: 'success', args: ...})", completionHandler: nil)

这些回调需要 调用 之前 存储在JavaScript中的哈希中postMessage,然后必须将哈希键发送到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];
}

当然,为您的项目添加NSCameraUsageDescriptionNSMicrophoneUsageDescription权限Info.plist

Keep in mind this is a non-trivial task, but that’s the general idea behind bridging JavaScript, WKWebView, and native framework code with asynchronous callbacks.

其他 2022/1/1 18:20:03 有420人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶