JS調用OC 很多應用裡面或多或少的調用了網頁,來達到絢麗的效果,所謂的JS調用OC.....舉個例子吧,網頁上有個按鈕 點擊按鈕跳轉界面,跳轉的動作由OC的代碼實現。 OC調用JS 還是舉個例子,我們OC代碼創建了輸入框比如輸入用戶名,輸入完成後顯示在網頁上,顯示用戶的用戶名 一.利用webVie ...
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.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調用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調用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"]; }