JS调用OC方法(JavaScriptCore)

一、JS 与OC交互一种方式是通过在JS与OC间定义一个协议,通过UIWebView的代理方法
-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
根据相应协议来实现JS向OC的传值过程。
通过协议传值(方法一)

二、JS 与OC交互的另一种方式是通过OC的JavaScriptCore框架
实现过程:
1、OC

 UIWebView *webView=[[UIWebView alloc]initWithFrame:self.view.bounds];

    NSString *path=[[NSBundle mainBundle]pathForResource:@"test" ofType:@"html"];
    NSURL *url=[NSURL fileURLWithPath:path];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    [self.view addSubview:webView];

    //得到JSContext对象
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"zwlog"] = ^() {

        //获取参数
        NSArray *args = [JSContext currentArguments];
        //打印内容
        for (JSValue *jsvalue in args) {
            NSLog(@"%@", jsvalue);
        }

    };

     self.webView=webView;
//第二中加载方式:
    NSString *path=[[NSBundle mainBundle]pathForResource:@"test" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSURL *url=[NSURL fileURLWithPath:path];
    [webView loadHTMLString:htmlString baseURL:url];

2、html代码

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
            <title></title>
    </head>

    <script type="text/javascript">
        function callOC(value1,value2){
         zwlog(value1+","+value2);
        }

        </script>
    <body bgcolor="#a9a9a9">
        <div style="text-align: center;margin-top: 50px">
          <input type="button" value="确定" onClick="callOC('11111','1')" />
        </div>
    </body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值