当前位置: 移动技术网 > IT编程>移动开发>IOS > Objective-C 代码与Javascript 代码相互调用实例

Objective-C 代码与Javascript 代码相互调用实例

2019年07月24日  | 移动技术网IT编程  | 我要评论

赵宝儿,2009年入党思想汇报,kiss表情

现在好的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.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"];
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网