0

I can successfully obtain a variable from javascript and display it as an alert message in an iOS app as follows:

    let loggedIn = self.webView.stringByEvaluatingJavaScript(from: "loggedIn");

    let alertController = UIAlertController(title: "iOScreator", message:
        loggedIn, preferredStyle: UIAlertControllerStyle.alert)
    alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))

    self.present(alertController, animated: true, completion: nil)

The above works perfectly. Is there a similar option to pass a variable from iOS to a javascript variable and run a function that does a pop alert with that variable?

Any help, as always, is appreciated. Many thanks, Alan.

Alan Tingey
  • 835
  • 11
  • 39
  • passing "loggedIn=true" will set loggedIn as true. similar way you can even call functions with parameters if you want. for reference https://stackoverflow.com/questions/3641968/passing-objective-c-variable-to-javascript-in-ios – Surya Subenthiran May 26 '17 at 14:20
  • Many thanks. Did not realise it was that simple. Feel free to put it as the answer. If you could pop an example of swift 3 and the function with parameter that would be great :) – Alan Tingey May 26 '17 at 14:27

1 Answers1

3

Swift code to call javascript method

self.webView.stringByEvaluatingJavaScript(from: "myFunction('param')")

javascript method

function myFunction(param)
{
    alert(param);
}

Reference passing objective c variable to javascript in ios

Hope this helps.

Surya Subenthiran
  • 2,217
  • 1
  • 15
  • 22