In order to establish communication between the web view(HTML) and the native code, we use the WKWebView and WKScriptMessage handler in native.
This way you can pass the event information from the WebView to the native code. Once the data received in the interface method, it will be sent to the backend through the datagran_iOS_sdk.
In order to pass the data from the HTML to native, you can use the WKUserContentController didReceiveScriptMessage which will handle it.
Example WebViewController
import UIKit
import WebKit
import datagran_iOS_sdk
class WebViewController: UIViewController {
@IBOutlet var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let userContentController = WKUserContentController()
userContentController.add(self,name: "datagran")
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
webView = WKWebView(frame: webView.bounds, configuration: configuration)
view.addSubview(webView)
let url = URL(string: "<https://app.datagran.io/>")
let request = URLRequest(url: url!)
webView.load(request)
}
}
extension WebViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print("message.body", message.body)
print("message.name", message.name)
print("userContentController", userContentController.self)
guard let body = message.body as? [String: Any] else { return }
guard let command = body["command"] as? String else { return }
if command == "trackCustom" {
let name = body["name"] as? String ?? ""
let params = body["parameters"] as? [String: NSObject] ?? [:]
Tracker.shared.trackCustom(viewName: name, action: params, controller: self, addGeo: false)
} else if command == "identify" {
let userId = body["userId"] as? String ?? ""
Tracker.shared.identify(id: userId, controller: self, addGeo: false)
} else if command == "reset" {
Tracker.shared.resetDGuserid()
/*
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "login") as! LoginTrackingViewController
nextViewController.modalPresentationStyle = .fullScreen
self.present(nextViewController, animated:true, completion:nil)*/
}
}
}