Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // WebViewController.swift
- // WebviewDemo
- //
- // Created by marco.rossi on 22/09/2019.
- // Copyright © 2019 marco.rossi. All rights reserved.
- //
- import UIKit
- import WebKit
- class WebViewController: UIViewController {
- private var webView: WKWebView!
- override func viewDidLoad() {
- super.viewDidLoad()
- let config = WKWebViewConfiguration()
- let userContentController = WKUserContentController()
- userContentController.add(self, name: "camera")
- userContentController.add(self, name: "data")
- config.userContentController = userContentController
- webView = WKWebView(frame: .zero, configuration: config)
- view.addSubview(webView)
- webView.translatesAutoresizingMaskIntoConstraints = false
- webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
- webView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
- webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
- webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
- if let url = URL(string: "https://demo.morphcast.com/native-app-webview/webview_index.html") {
- webView.load(URLRequest(url: url))
- }
- }
- }
- extension WebViewController: WKScriptMessageHandler {
- func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
- if message.name == "camera", let dict = message.body as? NSDictionary {
- if let maxSize = dict["value"] as? Int {
- onCameraFrame(maxSize: maxSize)
- }
- }
- if message.name == "data", let dict = message.body as? NSDictionary {
- if let type = dict["type"] as? String, let value = dict["value"] as? String {
- onData(type: type, value: value)
- }
- }
- }
- // JS Callbacks
- private func onCameraFrame(maxSize: Int) {
- /*
- App developer shall implement the following behaviour:
- 1) Retrieve a frame from camera
- * We suggest to resize frames before passing them to the WebView and to encode them in base64 format
- * Strings are processed faster than binary data through the JavaScript Interface
- 2) resize it to maxSize x maxSize (maintaining the aspect ratio)
- 3) Convert the frame to Base64
- 4) return the Base64 String
- */
- let base64Image = "..."
- let js = "resolveFrame(\(base64Image))"
- webView.evaluateJavaScript(js, completionHandler: nil)
- }
- private func onData(type: String, value: String) {
- /*
- type: String
- ["AGE","GENDER","EMOTION","FEATURES","POSE","AROUSAL_VALENCE","ATTENTION"]
- value: Json-stringified of the result
- App developer can use the values returned from the webview to implement the desired behavior (e.g update the App view, send data to a custom db ...)
- */
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement