关于IOS中与JavaScript的交互

IOS7中苹果提供了javascriptCore的框架,通过这个框架可以让OC与JavaScript之间的转换更加方便,这个框架基于之前的webkit库,现在被苹果引入标准库来使用,其中JSValue 的作用就是在 Objective-C 对象和 JavaScript 对象之间起转换作用,下面是转换的对应图: 屏幕快照 2013-11-18 下午3.33.04.png

执行javaScript脚本

可使用
- (JSValue *)evaluateScript:(NSString *)script;

[编辑]转换例子

  • 简单的数值转换
   JSContext *context = [[JSContext alloc] init];
   JSValue *jsVal = [context evaluateScript:@"21+7"];
   int iVal = [jsVal toInt32];
   NSLog(@"JSValue: %@, int: %d", jsVal, iVal);

   //Output:
   //  JSValue: 28, int: 28
  • NSArray的转换
   JSContext *context = [[JSContext alloc] init];
   [context evaluateScript:@"var arr = [21, 7 , 'iderzheng.com'];"];
   JSValue *jsArr = context[@"arr"]; // Get array from JSContext

   NSLog(@"JS Array: %@;    Length: %@", jsArr, jsArr[@"length"]);
   jsArr[1] = @"blog"; // Use JSValue as array
   jsArr[7] = @7;

   NSLog(@"JS Array: %@;    Length: %d", jsArr, [jsArr[@"length"] toInt32]);

   NSArray *nsArr = [jsArr toArray];
   NSLog(@"NSArray: %@", nsArr);

   //Output:
   //  JS Array: 21,7,iderzheng.com    Length: 3
   //  JS Array: 21,blog,iderzheng.com,,,,,7    Length: 8
   //  NSArray: (
   //   21, 
   //   blog,
   //   "iderzheng.com",
   //   "<null>",
   //   "<null>",
   //   "<null>",
   //   "<null>",
   //   7
   //   )
  • 关于block在JS中的使用
   JSContext *context = [[JSContext alloc] init];
   context[@"log"] = ^() {
       NSLog(@"+++++++Begin Log+++++++");

       NSArray *args = [JSContext currentArguments];
       for (JSValue *jsVal in args) {
           NSLog(@"%@", jsVal);
       }
  
       JSValue *this = [JSContext currentThis];
       NSLog(@"this: %@",this);
       NSLog(@"-------End Log-------");
       };

   [context evaluateScript:@"log('ider', [7, 21], { hello:'world', js:100 });"];
 
   //Output:
   //  +++++++Begin Log+++++++
   //  ider
   //  7,21
   //  [object Object]
   //  this: [object GlobalObject]
   //  -------End Log-------
相关链接:
 JavaScript into Native Applications - Tracy E
 JavaScriptCore and iOS 7
Execute Javascript in iOS Applications

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值