Mutual calls between JS Code and OC code, js Code oc
JS calls OC
Many applications call web pages more or less to achieve brilliant results. The so-called JS call OC... for example, there is a button on the web page.
Click the button to jump to the page. The jump is implemented by the OC code.
OC calls JS
For example, if the OC Code creates an input box, for example, enter the user name. After the input is complete, the user name is displayed on the webpage.
1. Use the webView proxy method to implement mutual calls between OC and JS
Create attributes
@ Property (nonatomic, strong) UIWebView * webView;
Comply with the webView protocol UIWebViewDelegate
-(Void) webViewLoad {NSURL * url = [[NSURL alloc] initWithString: @ "http://www.baidu.com"]; self. webView = [[UIWebView alloc] initWithFrame: self. view. bounds]; NSURLRequest * request = [[NSURLRequest alloc] initWithURL: url]; self. webView. delegate = self; [self. webView loadRequest: request]; [self. view addSubview: self. webView];} // JS call OC-(BOOL) webView :( UIWebView *) webView shouldStartLoadWithRequest :( NSURLRequest *) request navigationType :( UIWebViewNavigationType) navigationType {NSString * str = request. URL. relativeString; if ([str isEqualToString: @ "http://www.baidu.com/"]) {NSLog (@ "");} return YES;} // OC call JS-(void) webViewDidFinishLoad :( UIWebView *) webView {NSString * str = [self. webView stringByEvaluatingJavaScriptFromString: @ "document. getElementById ("\" index-kw ""\"). value = "" \ "li" "\" "]; NSLog (@" webViewDidFinishLoad = % @ ", str );}
2. Use a third-party framework (you need to name the same method as the html user)
-(Void) webViewBridge {self. webView = [[UIWebView alloc] initWithFrame: [UIScreen mainScreen]. bounds]; NSString * path = [[NSBundle mainBundle] pathForResource: @ "ExampleApp.html" ofType: nil]; NSURL * url = [[NSURL alloc] initFileURLWithPath: path]; [self. webView loadRequest: [NSURLRequest requestWithURL: url]; self. webView. delegate = self; [self. view addSubview: self. webView]; // set [WebViewJavascriptBridge enableLogging]; // set self for bridging. bridge = [WebViewJavascriptBridge bridgeForWebView: self. webView]; // set proxy [self. bridge setWebViewDelegate: self]; // JS call OC (testObjcCallback is the same method name as html) [self. bridge registerHandler: @ "testObjcCallback" handler: ^ (id data, WVJBResponseCallback responseCallback) {NSLog (@ "click"); self. view. backgroundColor = [UIColor blackColor]; responseCallback (@ "click") ;}] ;}// OC call JS-(void) webViewDidFinishLoad :( UIWebView *) webView {NSLog (@ "webViewDidFinishLoad"); [self. bridge callHandler: @ "registerHandler"];}