1. 程式人生 > >iOS 通過 JSPatch 實時修復線上 bug!

iOS 通過 JSPatch 實時修復線上 bug!

JSPatch 是一個開源專案(Github連結),只需要在專案裡引入極小的引擎檔案,就可以使用 JavaScript 呼叫任何 Objective-C 的原生介面,替換任意 Objective-C 原生方法。目前主要用於下發 JS 指令碼替換原生 Objective-C 程式碼,實時修復線上 bug。
除了實時修復線上 bug,甚至為 APP 動態新增一個模組也是可行的,不過可能會有效能問題。
使用JSPatch 需要有一個後臺可以下發和管理指令碼,並且需要處理傳輸安全等部署工作。
目前有一個JSPatch 平臺提供了一系列的服務,只需引入一個 SDK 就能使用 JSPatch,只是還在內測中….
地址 :

https://github.com/bang590/JSPatch

CocoPods安裝:

Podfile檔案

platform :ios, ‘6.0’
pod ‘JSPatch’

然後

pod install

下面開始使用:我們先建立一個列表,再通過JSPath改變行數

1.我們先在Controller里加入一個列表,讓他顯示3行 ,程式碼如下:

#import "JRViewController.h"

@interface JRViewController ()<UITableViewDataSource,UITableViewDelegate
>
@property(nonatomic,strong)UITableView* myTableView; @end @implementation JRViewController - (void)viewDidLoad { [super viewDidLoad]; UITableView* tv =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain]; self
.myTableView = tv; self.myTableView.delegate = self; self.myTableView.dataSource = self; [self.view addSubview:self.myTableView]; } #pragma mark -- UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return 3; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString* i= @"cell"; UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:i]; if (cell == nil ) { cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:i]; } cell.textLabel.text = @"title"; return cell; }

執行一下,顯示3行,沒問題

Paste_Image.png

2.建立js檔案 New File -> ios -> Empty …..

Paste_Image.png

3.在js檔案中 寫入:

//將JRViewController類中的- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section方法替換掉
defineClass('JRViewController', {
                tableView_numberOfRowsInSection: function(tableView, section) {
               return 10;
      },
});

4.呼叫這個js檔案,程式碼如下:

#import "AppDelegate.h"
#import "JPEngine.h"
@interface AppDelegate ()
@end
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   [JPEngine startEngine];
   NSString* path = [[NSBundle mainBundle]pathForResource:@"JSPathTest" ofType:@"js"];
   NSString* js = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
   [JPEngine evaluateScript:js];
   return YES;
}

執行一下,現在是顯示10行了 !

Paste_Image.png

**注:
如果我們想要通過 JS 指令碼替換原生 Objective-C 程式碼,實時修復線上 bug的話,還是要通過伺服器下發 js指令碼 ! **

程式碼如下:

[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://........"]]
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSString *script = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [JPEngine evaluateScript:script];
}];