Calling Swift function from JavaScript and JS function from Swift



When we develop a web app for iOS devices, we need to know how to call JavaScript function from Swift and also how to call Swift function from JavaScript.

Here let me bring you full codes for ViewController.swift and the html file that I loaded it locally.

ViewController.swift

//
//  ViewController.swift
//  Kitten Faces
//
//  Created by Macbook Pro on 12/22/17.
//  Copyright © 2017 Zofia Kreasi. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!
    
    @IBOutlet weak var button: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.webView.delegate = self
        self.loadHTMLFromBundle()
        
    }
    
    func loadHTMLFromBundle(){
        let url = Bundle.main.url(forResource: "index", withExtension: "html")
        let urlRequest:URLRequest = URLRequest(url:url!)
        self.webView.loadRequest(urlRequest)
        
    }

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


    @IBAction func changeP(_ sender: Any) {
        self.webView.stringByEvaluatingJavaScript(from: "changeP()")
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if request.url?.scheme == "wakwak" {
            self.webView.stringByEvaluatingJavaScript(from: "changeP()")
        }
        
        return true
    }
}

index.html

And here is the html file

<!DOCTYPE html>
<html>
    <head>
        <script>
            function changeP(){
                document.getElementById("p").innerHTML = "Josss pak!"
            }
        function sendmsg(){
            window.location = "wakwak://kukkuukukuku";
        }
        </script>
    </head>
    <body>
        <p id="p">Halo bibol!</p>
        <button onclick="sendmsg()">Change</P>
    </body>
</html>

URL Schemes

Another thing that you must configure is URL Schemes. Look what I’ve set here:

loading...

Leave a Reply

Your email address will not be published.