|
1 | 1 | # JavaScriptInterface |
2 | 2 | KWebView help you to call native code from Javascript in the iOS application. |
3 | 3 | Written by Swift 2.0. It's similar WebView.addJavascriptInterface in the Android application. |
| 4 | + |
| 5 | +## Setting your project |
| 6 | + |
| 7 | +Step 1: |
| 8 | +Expand the Link Binary With Libraries section and add the following item: |
| 9 | +JavaScriptCore.framework |
| 10 | + |
| 11 | +Step 2: |
| 12 | +- Define a protocol, inherit from JSExport protocol, which contains these native functions as you want to work with JavaScript. |
| 13 | +For example: |
| 14 | + |
| 15 | +```swift |
| 16 | +@objc protocol MyExport : JSExport |
| 17 | +{ |
| 18 | + func check(message : String) |
| 19 | + func sayGreeting(message: String, _ name: String) |
| 20 | + func anotherSayGreeting(message: String, name: String) |
| 21 | + func showDialog(title: String, _ message : String) |
| 22 | +} |
| 23 | +``` |
| 24 | + |
| 25 | +Step 3: |
| 26 | +Define a class to implement native functions above. |
| 27 | +```swift |
| 28 | +class JSInterface : NSObject, MyExport |
| 29 | +{ |
| 30 | + func check(message: String) { |
| 31 | + print("JS Interface works!") |
| 32 | + } |
| 33 | + |
| 34 | + func sayGreeting(message: String, _ name: String) |
| 35 | + { |
| 36 | + print("sayGreeting: \(message): \(name)") |
| 37 | + } |
| 38 | + |
| 39 | + func anotherSayGreeting(message: String, name: String) |
| 40 | + { |
| 41 | + print("anotherSayGreeting: \(message): \(name)") |
| 42 | + } |
| 43 | + |
| 44 | + func showDialog(title: String, _ message : String) |
| 45 | + { |
| 46 | + dispatch_async(dispatch_get_main_queue(), { |
| 47 | + UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: "OK").show() |
| 48 | + }) |
| 49 | + } |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +Step 4: |
| 54 | +From Indentity Inspector of your UIWebView, at Custom class section, update Class attribute to KWebView |
| 55 | + |
| 56 | +Step 5: |
| 57 | +Create an outlet to the webview in your view controller |
| 58 | +```swift |
| 59 | +@IBOutlet weak var webView : KWebView! |
| 60 | +``` |
| 61 | + |
| 62 | +Step 6: |
| 63 | +Add java script interface as below: |
| 64 | +```swift |
| 65 | +self.webView.addJavascriptInterface(JSInterface(), forKey: "Native"); |
| 66 | +``` |
| 67 | +##Usage |
| 68 | +Now to call those native functions above from JavaScipt is loaded your webview, just call: |
| 69 | + |
| 70 | +```swift |
| 71 | +Native.check() |
| 72 | + |
| 73 | +Native.sayGreeting('Hello', 'JavaScript Interface') |
| 74 | + |
| 75 | +``` |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + |
0 commit comments