4 thoughts on “iOS Swift to JavaScript Communication

  1. PERFECT! This is exactly what Im looking for. For those using Swift 3 see below that it worked for me

    class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!

    // runs slightly before viewDidLoad

    override func viewWillAppear(_ animated: Bool) {
    if let url = Bundle.main.url(forResource: “web/index”, withExtension: “html”) {
    // URL fragment, loaded app vs user touch, want to be able to tell the context of your app
    let frag = URL(string: “#FRAG_URL”, relativeTo: url)!
    let request = URLRequest(url: frag)

    webView.delegate = self //This view controller is webview delegate
    webView.loadRequest(request)

    }
    }

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }

    // Listens for URL requests and accepts them, stops or lets them go through
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    print(“request: \(request)”)
    if let scheme = request.url?.scheme {
    if scheme == “mike” {
    print(“we got a mike request: \(scheme)”)
    if let result = webView.stringByEvaluatingJavaScript(from: “someJavascriptFunc()”) {
    print(“result \(result)”)
    }// goes through global scope to find this function. Need to define in html

    return false;
    }
    }

    return true
    }
    }

  2. Its a great post. Crystal clear!!
    But is it possible to do the same for a remote webpage too?
    My usecase here is:
    I do not have the html file[as its remote]. I load a urlrequest. I need to call its one of the js functions. The same could be done very easily in android by just setting the javascript interface, but for iOS I am unable to do that.
    The js function actually returns a value and for retrieving that value I should set some key [No idea how to do that 🙁 ] Eg: The js function is something like this:
    function getContent() {
    if platform == “android” {
    android.callSomeOtherFunctionReturningTextValue()
    } else if platform == “ios” {
    ios.callSomeOtherFunctionReturningTextValue()
    }
    }
    Now this “ios”, I need to set in my webView.

    But in your sample there is no need of setting any such thing.
    Please help!

  3. Hi Monica,

    Did you find solution for above usecase? If you find please help me to solve it out facing the same issue. Thanks in advance.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.