Skip to content

Calling native code from Javascript in the iOS application likes addJavascriptInterface in the Android.

Notifications You must be signed in to change notification settings

giuseppefranco/JavaScriptInterface

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 

Repository files navigation

JavaScriptInterface

UIWebview extension help you to call native code from Javascript in the iOS application. Written by Swift 3.0. It's similar WebView.addJavascriptInterface in the Android application.

Setting your project

Step 1: Expand the Link Binary With Libraries section and add the following item: JavaScriptCore.framework

Step 2:

  • Define a protocol, inherit from JSExport protocol, which contains these native functions as you want to work with JavaScript. For example:
@objc protocol MyExport : JSExport
{
    func check(_ message : String)
    func sayGreeting(_ message: String, _ name: String)
    func anotherSayGreeting(_ message: String, name: String)
    func showDialog(_ title: String, _ message : String)
}

Step 3: Define a class to implement native functions above.

class JSInterface : NSObject, MyExport
{
    func check(_ message: String) {
        print("JS Interface works!")
    }
    
    func sayGreeting(_ message: String, _ name: String)
    {
        print("sayGreeting: \(message): \(name)")
    }
    
    func anotherSayGreeting(_ message: String, name: String)
    {
        print("anotherSayGreeting: \(message): \(name)")
    }

    func showDialog(_ title: String, _ message : String)
    {
        dispatch_async(dispatch_get_main_queue(), {
            UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: "OK").show()
        })
    }
}

Step 4: Create an outlet to the webview in your view controller

@IBOutlet weak var webView : UIWebView!

Step 5: Add java script interface as below at viewDidLoad:

self.webView.addJavascriptInterface(JSInterface(), forKey: "Native");

##Usage Now to call those native functions above from JavaScipt is loaded your webview, just call:

Native.check()

Native.sayGreeting('Hello', 'JavaScript Interface')

About

Calling native code from Javascript in the iOS application likes addJavascriptInterface in the Android.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift 93.7%
  • HTML 6.3%