標籤:
IOS產品開發中常常會遇到這種情況,線上發現一個嚴重bug,可能是一個crash,可能是一個功能無法使用,這時能做的只是趕緊修複Bug然後提交等待漫長的審核,即使申請加急也不會快到那裡去,即使審核完了之後,還要盼望著使用者快點升級,使用者不升級還是在存在同樣的漏洞,這樣的情況讓開發人員付出了很大的成本才能完成Bug的修複。
JSPath就是為瞭解決這樣的問題而出現的,只需要在項目中引入極小的JSPatch引擎,就可以還用JavaScript語言調用Objective-C的原生API,動態更新APP,修複BUG。
JSPaht本身是開源項目,項目地址:http://jspatch.com/,github地址: https://github.com/bang590/JSPatch
在他的官網上面給出了一個例子:
1 @implementation JPTableViewController 2 ... 3 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 4 { 5 NSString *content = self.dataSource[[indexPath row]]; //可能會超出數組範圍導致crash 6 JPViewController *ctrl = [[JPViewController alloc] initWithContent:content]; 7 [self.navigationController pushViewController:ctrl]; 8 } 9 ...10 @end
可以通過下發下面的JavaScript代碼修複這個bug:
1 //JS 2 defineClass("JPTableViewController", { 3 //instance method definitions 4 tableView_didSelectRowAtIndexPath: function(tableView, indexPath) { 5 var row = indexPath.row() 6 if (self.dataSource().length > row) { //加上判斷越界的邏輯 7 var content = self.dataArr()[row]; 8 var ctrl = JPViewController.alloc().initWithContent(content); 9 self.navigationController().pushViewController(ctrl);10 }11 }12 }, {})
JSPtch需要一個後台服務用來下發和管理指令碼,並需要處理傳輸安全等。
註冊擷取AppKey
在平台上面註冊一個賬戶,建立一個App可以拿到對應的AppKey。
匯入SDK到項目中
SDK地址:http://jspatch.com/Index/sdk
當前下載下來的SDK版本名稱是:JSPatch 2.framework,需要去掉中間的空格,不然匯入項目的時候會報錯。
匯入項目的時候要選擇Copy items if needed。
還需要添加對於的依賴架構JavaScriptCore.framework和libz.tbd.
添加JSPatch代碼
在AppDelegate.m中添加代碼:
1 #import "AppDelegate.h" 2 #import <JSPatch/JSPatch.h> 3 4 @implementation AppDelegate 5 6 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 7 [JSPatch startWithAppKey:@"f78378d77e5783e8"]; 8 [JSPatch sync]; 9 return YES;10 }11 @end在平台中上傳js修複檔案
為了簡單我們只上傳一個簡單的UIAlertView,彈出一個提示框:
1 ar alertView = require(‘UIAlertView‘).alloc().init();2 alertView.setTitle(‘Alert‘);3 alertView.setMessage(‘AlertView from js‘);4 alertView.addButtonWithTitle(‘OK‘);5 alertView.show();
用JavaScript執行個體化了UIAlertView,檔案名稱需要命名為main.js。
從伺服器下發到用戶端
把main.js上傳到伺服器上,下發到版本為1.0的用戶端上面。
在請求服務載入指令碼的時候出現了一個錯誤:The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.
這個錯誤出現的原因是ios9引入了新特性App Transport Security(ATS),簡單來說就是APP內部的請求必須使用HTTPS協議。
很明顯這裡的url並沒有使用https,我們可以通過設定先規避掉這個問題:
1.在info.plist中添加NSAppTransportSecurity類型為Dictionary.2.在NSAppTransportSecurity中添加NSAllowsArbitraryLoads類型為Boolean,值為YES
運行效果:
使用JSPatch平台熱修複iosApp