其实都是从袁峥Seemygo 这里学来的。
1、OC获取定义在JS中的变量,并通过OC直接修改JS中变量的值
-(void)getJSVar{
//创建JS代码
NSString *jsCode = @"var arr = [1,2,3]";
//创建js运行环境
JSContext *ctx = [[JSContext alloc]init];
//执行JS代码
[ctx evaluateScript:jsCode];
//执行完JS代码之后,获取JS变量,可以使用JSContext通过变量名称获取
JSValue *jsArr = ctx[@"arr"];
jsArr[0] = @5;
NSLog(@"%@",jsArr);
}
2017-04-01 09:49:44.809 React Native[12515:2883299] 5,2,3
2、OC调用JS方法,并获取返回结果
-(void)ocCallJSFunc{
NSString *jsCode = @"function hello(say){"
"return say;"
"}";
JSContext *ctx = [[JSContext alloc]init];
[ctx evaluateScript:jsCode];
JSValue *hello = ctx[@"hello"];//使用JSContext通过函数名称获取
JSValue *res = [hello callWithArguments:@[@"hello"]];//这里的参数需要一个数组
NSLog(@"%@",res);
}
2017-04-01 10:08:56.561 React Native[12553:2898397] hello
3、JS调用OC中不带参数的block
-(void)jsCallOCBlockWithoutArguments{
JSContext *ctx = [[JSContext alloc]init];
NSString *jsCode = @"eat()";
ctx[@"eat"] = ^(){
NSLog(@"吃");
};
[ctx evaluateScript:jsCode];
}
2017-04-01 10:24:14.918 React Native[12596:2906751] 吃
4、JS调用OC中带参数的block
-(void)jsCallBlockWithArguments{
JSContext *ctx = [[JSContext alloc]init];
ctx[@"eat"] = ^(){
NSArray *arguments = [JSContext currentArguments];
NSLog(@"吃%@",arguments[0]);
};
NSString *jsCode = @"eat('面包')";//注意'面包'
[ctx evaluateScript:jsCode];
}
2017-04-01 10:31:18.915 React Native[12625:2912073] 吃面包
5、JS调用OC 自定义类
在JS中并没有OC的类,需要在JS中生成OC的类,以及JS中的属性和方法也要在JS中生成
- 步骤:
- 自定义协议:
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
@protocol PersonJSExport <JSExport>
@property (nonatomic,strong)NSString *name;
-(void)play;
JSExportAs(playGame,-(void)playWithGame:(NSString *)game time:(NSString *)time);
@end
- 自定义类
#import "PersonJSExport.h"
@interface Person : NSObject<PersonJSExport>
@property (nonatomic,strong)NSString *name;
-(void)playWithGame:(NSString *)game time:(NSString *)time;
@end
#import "Person.h"
@implementation Person
-(void)play{
NSLog(@"%@玩",_name);
}
-(void)playWithGame:(NSString *)game time:(NSString *)time{
NSLog(@"%@在%@玩%@",_name,time,game);
}
@end
- JS调用自定义的类
-(void)jsCallCustonClass{
Person *p = [[Person alloc]init];
p.name =@"mudy";
JSContext *ctx = [[JSContext alloc]init];
ctx[@"onePerson"] = p;
NSString *jsCode = @"onePerson.playGame('王者荣耀','凌晨')";
// NSString *jsCode = @"onePerson.play()";
[ctx evaluateScript:jsCode];
}
2017-04-01 13:07:22.802 React Native[12952:2993038] mudy在凌晨玩王者荣耀