您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 動態熱修補技術 JSPatch 淺析

編輯:iOS 開發綜合

所謂動態熱修補,指的是當 App 出現嚴重 bug 時,若走 App Store 提交新版本、等待審核的週期太長、影響使用者體驗,就能藉由動態下發的方式即時修復,省去漫長的發版流程。

JSPatch 讓你能用 JavaScript 撰寫原生 iOS App。只需在專案裡引入一個極小的引擎,就能用 JavaScript 呼叫任何 Objective-C 的原生介面,享受腳本語言的優勢:為專案動態添加模組,或替換原生程式碼來修復 bug。

優缺點這裡不贅述,重點看實作。

(一)首先在終端搜尋:

 pod search JSPatch

接著可以用 pod 把它引入專案,或下載到本地手動加入。搜尋結果如下:

 -> 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] 

一般我們會把要執行的 .js 檔放在伺服器端,每次 App 啟動時比對本地與伺服器端的 js 是否變化,再決定是否更新。細節這裡不多談。

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 加載引擎 [JPEngine startEngine]; // 本地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:@"https://cnbang.net/test.js"]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *script = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; [JPEngine evaluateScript:script]; }]; } 

這是大致流程。接著舉個小例子,說明 js 如何替換原生方法。先看一段 js,示範 Objective-C 與 js 的互動:

 //按鈕事件 defineClass('YFJSPatchMainViewController', { buttonTouch: function(button) { var tableViewCtrl = YFJSPatchTsetViewController.alloc().init() self.navigationController().pushViewController_animated(tableViewCtrl, YES) } })

意思其實很直白:這段 js 找到 YFJSPatchMainViewController 類裡的 buttonTouch: 方法。原本這個方法可以是空的,當 js 執行後,這個方法就會改為執行 js 裡定義的邏輯,進而觸發 push 跳轉。

 -(void)buttonTouch:(uibutton)btn { }

原理就是這樣,最好親手實作一次才會有感。祝你玩得愉快!

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved