JavaScript to Swift communication

Hey guys,


Programming environemnt :

swift version : 4.0

xcode version : 9.2


My objective :

1- Open a web application in ios and

2 - Communicate with its elements using JavaScript - invoke a method in my native app


what I have done so far :

I can load my application using webkit view.


challenges :

I found few old instructions for invoking native code from web applications JS functions which sadly won't work in newer versions of swift. due to swift upgrade.

function/methods like : NSBundle that are no longer available.

Main Question :

how can I invoke a method in native app from JavaScript

Thank you

Replies

how can I invoke a method in native app from JavaScript

That depends on what type of web view you’re using. The recommended web view for this sort of thing is

WKWebView
. In that view you can invoke native methods from JavaScript via the
WKScriptMessage
mechanism:
  1. When you create the web view, you have to pass in a

    WKWebViewConfiguration
    . Add yourself as a script message handler for the message in question:
    webViewConfiguration.userContentController.add(self, name: "myMessageName")

    .

  2. In JavaScript, send a message with code like this:

    window.webkit.messageHandlers.myMessageName.postMessage(message)

    .

  3. Back in native, this will call the script message handler method that you registered:

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        assert(message.name == "myMessageName")
        … handle the message …
    }

    .

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
  • Hi this is excellent and worked perfectly for what I need.

    Does anyone know how I can do this the other way? So from Swift to Javascript?

    Thanks,

    Chris

  • you can use webView.evaluateJavaScript or WKUserContentController to add user script.

Add a Comment