zoukankan      html  css  js  c++  java
  • iOS开发:JavaScriptCore.framework的简单使用--JS与OC的交互篇

    iOS7之后苹果为众猿推出了JavaScriptCore.framework这个框架,这个框架为大家在与JS交互上提供了很大帮助,可以在html界面上调用OC方法并传参,也可以在OC上调用JS方法并传参.这里简单的介绍一下这个框架的使用.

    javaScriptCore是一种JavaScript引擎,主要为webKit提供脚本处理能力,javaScriptCore是开源webkit的一部分,他提供了强大的整合能力.下面以JS调用OC方法为例,OC调用JS为例说明.

    • JSContext, JSContext是代表JS的执行环境,通过-evaluateScript:方法就可以执行一JS代码
    • JSValue, JSValue封装了JS与ObjC中的对应的类型,以及调用JS的API等
    • JSExport, JSExport是一个协议,遵守此协议,就可以定义我们自己的协议,在协议中声明的API都会在JS中暴露出来,才能调用

    1.首先,导入JavaScriptCore.framework这个框架,target-->Build Phases-->Link Binary With Libraies添加这个框架.

    2.在使用了文件里添加头文件

    #import <JavaScriptCore/JavaScriptCore.h>

    3.为了演示方便,这里我们写了一个本地的Test.html,使用webView加载Test.html.

    这里,我们需要使用JavaScriptCore.framework这个框架里面的JSContext这个代表了获取到JS的运行环境.

    1 @property (nonatomic,strong) UIWebView * webView;
    2 @property (nonatomic,weak) JSContext * context;

    4.在.m文件中,加载html文件.viewDidLoad

     1     //创建一个webView来加载html
     2     _webView = [[UIWebView alloc]init];
     3     _webView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/2);
     4     _webView.delegate = self;
     5     [self.view addSubview:_webView];
     6     
     7     //先加载一个本地的html
     8     NSString * path = [[NSBundle mainBundle] pathForResource:@"Test.html" ofType:nil];
     9 //    NSLog(@"%@",path);
    10     NSURL * url = [[NSURL alloc]initFileURLWithPath:path];
    11 //    NSLog(@"%@",url);
    12     NSURLRequest * request = [NSURLRequest requestWithURL:url];
    13     [_webView loadRequest:request];

    5.创建两本原生button,演示OC调用JS方法.html中也写两个按钮和方法,用于演示JS调用OC.

     1     //创建两个原生button,演示调用js方法
     2     UIButton * btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
     3     btn1.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height/2, 200, 50);
     4     btn1.backgroundColor = [UIColor blackColor];
     5     [btn1 setTitle:@"OC调用无参JS" forState:UIControlStateNormal];
     6     [btn1 addTarget:self action:@selector(function1) forControlEvents:UIControlEventTouchUpInside];
     7     [self.view addSubview:btn1];
     8     UIButton * btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
     9     btn2.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height/2+100, 200, 50);
    10     btn2.backgroundColor = [UIColor blackColor];
    11     [btn2 setTitle:@"OC调用JS(传参)" forState:UIControlStateNormal];
    12     [btn2 addTarget:self action:@selector(function2) forControlEvents:UIControlEventTouchUpInside];
    13     [self.view addSubview:btn2];

    html中

     1 <html>
     2 <head>
     3     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
     4     <title>hello World</title>
     5 </head>
     6 
     7 <script type="text/javascript">
     8 
     9     function JSCallOc1(){
    10     test1();
    11     }
    12    function JSCallOc2(){
    13     test2('少停','iOS');
    14    }
    15   function aaa(){
    16       alert("OC调用了无参数的js方法");
    17   }
    18   function bbb(name,num){
    19       alert(name+num);
    20   }
    21 
    22 </script>
    23 
    24 <body bgcolor="#555555">
    25   <button type="button"  onclick="JSCallOc1()">JS调用OC方法(无参)</button>
    26   <button type="button"  onclick="JSCallOc2()">JS调用OC方法(传参)</button>
    27 </body>
    28 </html>

    准备工作完毕,下面演示JS与OC的交互.

    UIWebViewDelegate方法中,有四个代理方法,开发中我们可以使用这几个方法在不同的时刻做不同的事情.

     1 #pragma UIWebViewDelegate方法
     2 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
     3     NSLog(@"开始响应请求时触发");
     4     return YES;
     5 }
     6 - (void)webViewDidStartLoad:(UIWebView *)webView{
     7     NSLog(@"开始加载网页");
     8 }
     9 - (void)webViewDidFinishLoad:(UIWebView *)webView{
    10     NSLog(@"网页加载完毕");
    11  
    12 }
    13 - (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{
    14     NSLog(@"网页加载出错");
    15 
    16 }

    JS调用OC方法并且传参

    这里,我们在网页加载完毕之后让JS调用OC的方法并传参数.

     1 - (void)webViewDidFinishLoad:(UIWebView *)webView{
     2     NSLog(@"网页加载完毕");
     3     //获取js的运行环境
     4     _context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
     5     //html调用无参数OC
     6     _context[@"test1"] = ^(){
     7         [self menthod1];
     8     };
     9     //html调用OC(传参数过来)
    10     _context[@"test2"] = ^(){
    11         NSArray * args = [JSContext currentArguments];//传过来的参数
    12 //        for (id  obj in args) {
    13 //            NSLog(@"html传过来的参数%@",obj);
    14 //        }
    15         NSString * name = args[0];
    16         NSString * str = args[1];
    17         [self menthod2:name and:str];
    18     };
    19 }

    html里面

    <body bgcolor="#555555">
      <button type="button"  onclick="JSCallOc1()">JS调用OC方法(无参)</button>
      <button type="button"  onclick="JSCallOc2()">JS调用OC方法(传参)</button>
    </body>
        function JSCallOc1(){
        test1();
        }
       function JSCallOc2(){
        test2('少停','iOS');
       }

    如上所示,先行建立一个context来获取到JS的开发环境,使用一个block来执行OC方法.其中[@"test1"]中的test1需要和JS中的一致.

    至于传参,]JSContext currentArguments]可以获取到js传过来的参数数组.那么就可以获取数组中值来使用了.接着我们就可以在这个block中调用OC的方法并且使用这些参数了.

    1 #pragma 供JS调用的方法
    2 -(void)menthod1{
    3     NSLog(@"JS调用了无参数OC方法");
    4 }
    5 -(void)menthod2:(NSString *)str1 and:(NSString *)str2{
    6     NSLog(@"%@%@",str1,str2);
    7 }

    OC调用JS方法并且传参

    至于OC调用JS方法也很简单,使用下面这个对象方法即可

    - (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;

    1 #pragma OC调用JS方法
    2 -(void)function1{
    3    [_webView stringByEvaluatingJavaScriptFromString:@"aaa()"];
    4 }
    5 -(void)function2{
    6     NSString * name = @"pheromone";
    7     NSInteger num = 520;//准备传去给JS的参数
    8    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"bbb('%@','%ld');",name,num]];
    9 }

    html里面

      function aaa(){
          alert("OC调用了无参数的js方法");
      }
      function bbb(name,num){
          alert(name+num);
      }

      也可以在OC中直接写JS代码来执行

    1     //1.直接调用
    2     NSString *alertJS=@"alert('test js OC')"; //准备执行的js代码
    3     [_context evaluateScript:alertJS];

    演示截图:

    以上就是有关JavaScriptCore.framework这个框架的简单使用.有关参考文档:

    对于JavaScriptCore.framework的介绍:http://www.webryan.net/2013/10/about-ios7-javascriptcore-framework/

                                                                   http://nshipster.cn/javascriptcore/

    对于另外一个三方库WebViewJavascriptBridge的使用:http://blog.csdn.net/remote_roamer/article/details/7261490

    本文源码下载地址:http://download.csdn.net/detail/shaoting19910730/9453841

                            https://github.com/pheromone/JavaScriptCore_demo/tree/master

  • 相关阅读:
    HDU 3572 Task Schedule(拆点+最大流dinic)
    POJ 1236 Network of Schools(Tarjan缩点)
    HDU 3605 Escape(状压+最大流)
    HDU 1166 敌兵布阵(分块)
    Leetcode 223 Rectangle Area
    Leetcode 219 Contains Duplicate II STL
    Leetcode 36 Valid Sudoku
    Leetcode 88 Merge Sorted Array STL
    Leetcode 160 Intersection of Two Linked Lists 单向链表
    Leetcode 111 Minimum Depth of Binary Tree 二叉树
  • 原文地址:https://www.cnblogs.com/shaoting/p/5247208.html
Copyright © 2011-2022 走看看