I am developing a hybrid application for iOS. In order to achieve two way communication between Javascript and the native code, I am using Webviewjavascriptbridge
, a third-party library. This is the code that I am using.
//pkViewcontroller.h
@class WebViewJavascriptBridge;
@property (strong, nonatomic) WebViewJavascriptBridge *javascriptBridge;
@property (strong, nonatomic) IBOutlet UIWebView *webView;
//pkViewcontroller.m
- (void)viewDidLoad
{
[WebViewJavascriptBridge enableLogging];
_bridge= [WebViewJavascriptBridge bridgeForWebView:_webView handler:nil];
NSString *path=[[NSBundle mainBundle]pathForResource:@"index" ofType:@"html"];
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
[_webView loadRequest:request];
[_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponse *response) {
NSLog(@"after getContactBttnTapped method call");
ABPeoplePickerNavigationController *picker=[[ABPeoplePickerNavigationController alloc]init];
picker.peoplePickerDelegate= self;
[self presentViewController:picker animated:YES completion:nil];
}];
}
HTML file
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<input type="Button" value="ChooseContact" onClick="ChooseContactTapped()">
</body>
</html>
test.js
var bridge
window.onerror = function(err) {
alert('window.onerror: ' + err)
}
document.addEventListener('WebViewJavascriptBridgeReady', onBridgeReady, false)
function onBridgeReady(event) {
bridge = event.bridge
}
function ChooseContactTapped(){
bridge.callHandler('testObjcCallback', {'foo': 'bar'}, function(response) {
log('Got response from testObjcCallback', response)
})
}
The JS file will be residing on the server. Now I want to call my native method without writing the code inside the JS file. Please help me. If what I am doing is not correct, please suggest me a way to make the communication between native code and Javascript. Please note that the JS file will be on the server and also I need to pass objects between JS and the native code.