JavaScriptCore使用案例及Native与JavaScript交互之内部结构剖析

  1. JSVirtualMachine
    JavaScript代码是在创建JSVirtualMachine类的虚拟机下执行,不能在两个不同JSVirtualMachine类之间进行数据传输,每个JSVirtualMachine类实例有自己的堆和垃圾回收器.

  2. JSContext
    一个JSContext对象代表一个JavaScript代码执行环境,是一个全局对象,它在web开发中等同于一个window对象,同一个JSVirtualMachine类下不同的JSContext之间可以自由传值。

  3. JSValue

    是一个主要的数据类型,能够代表任何可能的JavaScript的值,一个JSValue的实例绑定到它所在的JSContext对象中。
    jscore01.png
  4. JSExport

    一种协议提供了声明式的方法去向JavaScript代码导出Objective-C的实例类及其实例方法,类方法和属性
    jscore02.gif
    第一步请求JavaScript网络数据解析并转换为Objective-C中对象模型数组:
    //懒加载JSContext
-(JSContext *)context{
    
    if (_context == nil) {
        
        _context = [[JSContext alloc] init];
        
      NSString *commonJSPath=[[NSBundle mainBundle] pathForResource:@"common" ofType:@"js"];
      NSString *additionsJSPath=[[NSBundle mainBundle] pathForResource:@"additions" ofType:@"js"];
    
      NSString *commomStr=[NSString stringWithContentsOfFile:commonJSPath encoding:NSUTF8StringEncoding error:nil];
    
      NSString *additionsStr=[NSString stringWithContentsOfFile:additionsJSPath encoding:NSUTF8StringEncoding error:nil];
        
        //将OC中的Movie类对象和JavaScript中的Movie对象桥接在一起
        [_context setObject:[Movie self] forKeyedSubscript:@"Movie"];
        
        //执行js代码
        [_context evaluateScript:commomStr];
        [_context evaluateScript:additionsStr];
    }
    
    return _context;
}

-(void)loadMoviesWith:(double)limit  moviesBlock:(void(^)(NSArray *movies))moviesBlock
{
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    
    NSURLSessionDataTask *dataTask=[mgr GET:MovieURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
     NSString *jsonString=[self switchObjectToJSON:responseObject];
      
      //解析JSON数据并传出Movie模型数组
      moviesBlock([self parseResponseObject:jsonString limit:limit]);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"MovieViewData Load Error %@",error);
    }];
    
    [dataTask resume];   
}

//解析JSON数据
-(NSArray *)parseResponseObject:(NSString *)response limit:(double)limit{
    
    //1
   JSValue *parseFunction=[self.context objectForKeyedSubscript:@"parseJson"];
   NSArray *parsed=[[parseFunction callWithArguments:@[response]] toArray];
    
    //2
   JSValue *filterFunction=[self.context objectForKeyedSubscript:@"filterByLimit"];
   NSArray *filtered=[filterFunction callWithArguments:@[parsed,@(limit)]].toArray;
    
    //3
    return [self switchDictionaryArrayToModelArrayWith:filtered];
}

第二步自定义cell中数据设置:

    -(void)setMovie:(Movie *)movie
{
    _movie=movie;
    _nameLabel.text=movie.title;
    _priceLabel.text=movie.price;
    [_imageView sd_setImageWithURL:[NSURL URLWithString:movie.imageUrl]];
}

第三部在控制器调用并加载数据:

-(NSArray *)movies
{
    if (_movies == nil) {
        
        _movies=[[NSArray alloc] init];
    }
    return _movies;
}
#pragma mark -- UITextFieldDelegate

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //调用此方法 触发textFieldDidEndEditing:方法调用
    [textField resignFirstResponder];
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    double number=[textField.text doubleValue];
    MovieViewData *mvData= [[MovieViewData alloc] init];

    [mvData loadMoviesWith:number moviesBlock:^(NSArray *movies) {
        self.movies=movies;
        [self.collectionView reloadData];
    }];
}
#pragma mark -- UICollectionViewDataSource

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.movies.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   MovieViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:MovieViewCellID forIndexPath:indexPath]; 
    cell.movie=self.movies[indexPath.row];
    return cell;
}

原生应用与JavaScript交互之内部结构剖析:
jscore03.png

推荐阅读更多精彩内容