Skip to content

Commit e67100f

Browse files
committed
Update README.md
1 parent e1157d7 commit e67100f

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

README.md

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,72 @@
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+
@objc protocol MyExport : JSExport
15+
{
16+
func check(message : String)
17+
func sayGreeting(message: String, _ name: String)
18+
func anotherSayGreeting(message: String, name: String)
19+
func showDialog(title: String, _ message : String)
20+
}
21+
22+
Step 3:
23+
Define a class to implement native functions above
24+
For example:
25+
class JSInterface : NSObject, MyExport
26+
{
27+
func check(message: String) {
28+
print("JS Interface works!")
29+
}
30+
31+
func sayGreeting(message: String, _ name: String)
32+
{
33+
print("sayGreeting: \(message): \(name)")
34+
}
35+
36+
func anotherSayGreeting(message: String, name: String)
37+
{
38+
print("anotherSayGreeting: \(message): \(name)")
39+
}
40+
41+
func showDialog(title: String, _ message : String)
42+
{
43+
dispatch_async(dispatch_get_main_queue(), {
44+
UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: "OK").show()
45+
})
46+
}
47+
}
48+
49+
50+
Step 4:
51+
From Indentity Inspector of your UIWebView, at Custom class section, update Class attribute to KWebView
52+
53+
Step 5:
54+
Create an outlet to the webview in your view controller
55+
@IBOutlet weak var webView : KWebView!
56+
57+
Step 6:
58+
Add java script interface as below:
59+
self.webView.addJavascriptInterface(JSInterface(), forKey: "Native");
60+
61+
# Inuse
62+
63+
Now to call those native functions above from JavaScipt is loaded your webview, just call:
64+
65+
Native.check()
66+
Native.sayGreeting('Hello', 'JavaScript Interface')
67+
..
68+
69+
70+
71+
72+

0 commit comments

Comments
 (0)