Skip to content

Commit 8928cae

Browse files
committed
Merge remote-tracking branch 'origin/master'
2 parents 95042ce + 0a16ebe commit 8928cae

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

README.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,79 @@
11
# JavaScriptInterface
22
KWebView help you to call native code from Javascript in the iOS application.
33
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

Comments
 (0)