其實都是從袁崢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在凌晨玩王者榮耀