简体   繁体   中英

Objective-C - Javascript communication

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.

As per our discussion,

Here is the way to solve this problem.

It is quite task, but you can attain what you want to do.

-Call a service and you can send all objects' contents in xml.

-Parse that xml and form a data class.

-Build a Data class from that xml.

-In the end you will have a copy of Object in cocoa that you wish to pass from server using JS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM