iOS之 动态热修补技术JSPatch

jopen 8年前

 

所谓动态热修补就是把能够导致app 崩溃的严重bug,提交新版本到appstore 审核速度太慢影响用户使用,这时候就可以利用

JSPatch 可以让你用 JavaScript 书写原生 iOS APP。只需在项目引入极小的引擎,就可以使用 JavaScript 调用任何 Objective-C 的原生接口,获得脚本语言的优势:为项目动态添加模块,或替换项目原生代码动态修复 bug。

这里就不在赘述优缺点重点看实现!

(一)首先在终端

pod search JSPatch

接下来就可以自己pod进你需要引入的工程中,或者download到本地自己加到工程中搜索结果如下

-> JSPatch (0.1.4)    JSPatch bridge Objective-C and JavaScript. You can call any Objective-C class    and method in JavaScript by just including a small engine.    pod 'JSPatch', '~> 0.1.4'    - Homepage: https://github.com/bang590/JSPatch    - Source: https://github.com/bang590/JSPatch.git    - Versions: 0.1.4, 0.1.3, 0.1.2, 0.1.1, 0.1, 0.0.3, 0.0.2, 0.0.1 [master    repo] - 0.1.4, 0.1.3, 0.1.2, 0.1.1, 0.1, 0.0.3, 0.0.2, 0.0.1 [master-1 repo]    - Subspecs:      - JSPatch/Core (0.1.4)      - JSPatch/Extensions (0.1.4)  macxy:~ xy$

一般我们将执行的".js"文件放在服务器端每次程序启动时候可以执行比对本地js文件与服务器端js文件是否有变化这里细节就不做解释
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {     // 加载引擎    [JPEngine startEngine];  // 本地JS,动态更新技术就是通过服务器获取JS更新这个JS    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"js"];    NSString *script = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil];    [JPEngine evaluateScript:script];    从服务器获取更新JS    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cnbang.net/test.js"]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {      NSString *script = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];      //执行js      [JPEngine evaluateScript:script];    }];  }

这是大概过程举个小栗子描述下js替换的具体应用;

先上一段js文件解释下oc与js交互如何访问oc API

//按钮事件  defineClass('YFJSPatchMainViewController', {//哪个类中的方法    buttonTouch: function(button) {//方法名:function(参数)  //跳转到tableView      var tableViewCtrl = YFJSPatchTsetViewController.alloc().init()  self.navigationController().pushViewController_animated(tableViewCtrl, YES) } })

相信大家也都看的懂那么我们要怎么去用呢比如   我上面所写的就是要找到

YFJSPatchMainViewController这个类中的
-(void)buttonTouch:(uibutton)btn  {  }  这个方法最开始我们什么都没有写,当执行完js文件后这个方法就会去执行js  然后push;原理就是这样要自己去用一下才好祝您愉快