public static void FireUnityJavascriptEvent(string method, object data)
{
UIViewController viewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
JavaScriptSerializer Serialiser = new JavaScriptSerializer();
string dataJSONString = "null";
if (data != null)
{
dataJSONString = Serialiser.Serialize(data);
if (data is String)
{
dataJSONString = "'" + (data as String) + "'";
}
}
string jsCallbackFunction = "if(" + method + "){" + method + "(" + dataJSONString + ");}";
//only for testing
SystemLogger.Log(SystemLogger.Module.PLATFORM, "NotifyJavascript (single object): " + method + ", dataJSONString: " + dataJSONString);
bool webViewFound = false;
if (viewController != null && viewController.View != null)
{
UIView[] subViews = viewController.View.Subviews;
foreach (UIView subView in subViews)
{
if (subView is UIWebView)
{
webViewFound = true;
// evaluate javascript as a UIWebView
(subView as UIWebView).EvaluateJavascript(jsCallbackFunction);
}
else if (subView is WKWebView)
{
webViewFound = true;
// evaluate javascript as a WKWebView
(subView as WKWebView).EvaluateJavaScript(new NSString(jsCallbackFunction), delegate(NSObject result, NSError error) {
SystemLogger.Log(SystemLogger.Module.PLATFORM, "NotifyJavascript COMPLETED (" + method + ")");
});
}
}
}
if (webViewFound)
{
SystemLogger.Log(SystemLogger.Module.PLATFORM, "NotifyJavascript EVALUATED (" + method + ")");
}
else
{
SystemLogger.Log(SystemLogger.Module.PLATFORM, "It was not possible to find a WebView to evaluate the javascript method");
}
}