WebView 接入文档
WebView的初始化
let configuration = WKWebViewConfiguration()
configuration.allowsInlineMediaPlayback = true
configuration.mediaTypesRequiringUserActionForPlayback = .video
configuration.userContentController.add(self, name: "jsBridge")
let webView = WKWebView(frame: CGRect(x: 0, y: CGRectGetMaxY(navView.frame), width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - CGRectGetMaxY(navView.frame) - 70 - bottom_height), configuration: configuration)
view.addSubview(webView)
WebView加载指定网页
let url = URL(string: "https://demo.deepscience.cn/poc/index.html")
let request = URLRequest(url: url!, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 60)
webView.load(request)
WebView中执行js函数
webView.evaluateJavaScript("SendMsgToWebGL('{\"type\":\"ChangeCharacter\",\"data\":\"\(robot.abName)\"}')")
webView.evaluateJavaScript("SendMsgToWebGL('{\"type\":\"AudioBroadcast\",\"data\":\"https://ds-model-tts.oss-cn-beijing.aliyuncs.com/temp/167144092926757110.wav\"}')")
webView.evaluateJavaScript("SendMsgToWebGL('{\"type\":\"TextBroadcast\",\"data\":\"\(text)\",\"bodyMotion\":\"3\"}')")
webView.evaluateJavaScript("SendMsgToWebGL('{\"type\":\"TextAnswerMotion\",\"data\":\"\(text)\",\"bodyMotion\":\"3\"}')")
webView.evaluateJavaScript("SendMsgToWebGL('{\"type\":\"AudioAnswerMotion\",\"data\":\"\(detail)\"}')")
webView.evaluateJavaScript("SendMsgToWebGL('{\"type\":\"BroadcastStop\",\"data\":\"null\"}')")
WebView网页加载完成的回调
webView.navigationDelegate = self;
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("网页加载完成")
}
APP收到WebView发过来的js消息
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "jsBridge" {
print(message.body)
}
}