5

I am developing a hybrid Android and iOS app using WebViews. However, I am struggling to return data from iOS app back to my Javascript.

Below is how I setup the WebView to receive data from my JavaScript functions.

private lazy var webViewConfiguration: WKWebViewConfiguration = {
    let configuration = WKWebViewConfiguration()
    configuration.userContentController.add(self, name: "loginController")
    return configuration
}()


extension ApplicationController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    if (message.name == "loginController"){
        print("\(message.body)")
    }
}
}

This is how I pass data to the app.

webkit.messageHandlers.loginController.postMessage("Hello from JavaScript");

Essentially, what I'd like to do is be able to receive data back from the app to my JavaScript and do something along the lines of this...

var response = webkit.messageHandlers.loginController.postMessage("Hello from JavaScript");

But I cannot figure out how to return something from the app. I'm new to Swift. However for Android dev it can be as simple as adding a return type to my function, but this does not work for Swift.

tinOfBeans
  • 537
  • 1
  • 8
  • 21
  • 1
    There exists the [evaluateJavaScript](https://developer.apple.com/documentation/webkit/wkwebview/1415017-evaluatejavascript?language=swift) method. You can use it to return data to JavaScript. This mechanism is asynchronous, I have yet to find a way to make the WKWebView do this synchronously like we do in Android or [in the UIWebView](https://stackoverflow.com/questions/26851630/javascript-synchronous-native-communication-to-wkwebview). – paulvs Jul 10 '17 at 22:18

0 Answers0