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