2 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


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

    override func 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

Leave a Reply

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