JS代码和OC代码的相互调用

时间:2023-03-08 16:38:16

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"];
}