如今好的IOS 的 APP有時刻會跟網頁內容相干聯,固然也是增長用戶體驗,及更好的,有用的表現APP 的功效。
因為自己在項目中會用到這部門功效,做下記載!
JS挪用OC
許多運用外面或多或少的挪用了網頁,來到達壯麗的後果,所謂的JS挪用OC.....舉個例子吧,網頁上有個按鈕
點擊按鈕跳轉界面,跳轉的舉措由OC的代碼完成。
OC挪用JS
照樣舉個例子,我們OC代碼創立了輸出框好比輸出用戶名,輸出完成後顯示在網頁上,顯示用戶的用戶名
一.應用webView的署理辦法完成OC和JS的互相挪用
創立屬性
@property(nonatomic,strong)UIWebView * webView;
遵照webView的協定UIWebViewDelegate
-(void)webViewLoad{ NSURL * url = [[NSURL alloc]initWithString:@"http://www.百度.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挪用OC -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ NSString * str = request.URL.relativeString; if ([str isEqualToString:@"http://www.百度.com/"]) { NSLog(@"來找度娘"); } return YES; } //OC挪用JS -(void)webViewDidFinishLoad:(UIWebView *)webView{ NSString * str = [self.webView stringByEvaLuatingJavaScriptFromString:@"document.getElementById(""\"index-kw""\").value=""\"li""\""]; NSLog(@"webViewDidFinishLoad=%@",str); }
二.應用第三方的框架完成(須要你和html真個人同一辦法的稱號)
-(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]; //設置可以或許橋接 [WebViewJavaScriptBridge enableLogging]; //設置橋接 self.bridge = [WebViewJavaScriptBridge bridgeForWebView:self.webView]; //設置署理 [self.bridge setWebViewDelegate:self]; //JS挪用OC(testObjcCallback是和html同一的辦法名字) [self.bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) { NSLog(@"按鈕點擊了"); self.view.backgroundColor= [UIColor blackColor]; responseCallback(@"按鈕點擊了"); }]; } //OC挪用JS -(void)webViewDidFinishLoad:(UIWebView *)webView{ NSLog(@"webViewDidFinishLoad"); [self.bridge callHandler:@"registerHandler"]; }
感激浏覽,願望能贊助到年夜家,感謝年夜家對本站的支撐!
【Objective-C 代碼與Javascript 代碼互相挪用實例】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!