iOS之 動態熱修補技術JSPatch

jopen 9年前發布 | 22K 次閱讀 JSPatch iOS開發 移動開發

 

所謂動態熱修補就是把能夠導致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$</pre>
      一般我們將執行的".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;原理就是這樣要自己去用一下才好祝您愉快


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!