IOS App常常會遇到這種情況,線上發現一個嚴重bug
,可能是某一個地方Crash
,也可能是一個功能無法使用,這時能做的只有趕緊修復Bug然后提交app store
等待漫長的審核。
即使申請加急審核但是審核速度仍然不會快到那里去,即使審核完了之后,還要盼望著用戶快點升級,用戶不升級同樣的漏洞一直存在,這種情況讓開發者付出了很大的成本才能完成對于Bug
的修復,有可能還需要出現強制升級的情況。
這樣情況現在有辦法改善,JSPatch
就是為了解決這樣的問題而出現的,只需要在項目中引入極小的一個JSPatch
引擎,就可以使用JavaScript
語言調用Objective-C
的原生API,動態更新App,修復BUG。
JSPatch
是一個開源的項目,項目網站:http://jspatch.com/,Github地址: https://github.com/bang590/JSPatch
在JSPatch
的官網上面給出了一個例子:
@implementation JPTableViewController
...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *content = self.dataSource[[indexPath row]]; //可能會超出數組范圍導致crash
JPViewController *ctrl = [[JPViewController alloc] initWithContent:content];
[self.navigationController pushViewController:ctrl];
}
...
@end
這里會出現一個數組越界的Crash
可以通過下發下面的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
需要一個后臺服務用來下發和管理腳本,并需要處理傳輸安全等JSPatch
平臺提供了對應的服務。
注冊獲取AppKey
在JSPatch
平臺上面注冊一個賬戶,新建一個App就可以拿到對應的AppKey。
導入SDK到項目中
SDK地址:http://jspatch.com/Index/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
在平臺中上傳JavaScript
修復文件
為了簡單我們只上傳一個簡單的UIAlertView
,彈出一個提示框:
ar alertView = require('UIAlertView').alloc().init();
alertView.setTitle('Alert');
alertView.setMessage('AlertView from js');
alertView.addButtonWithTitle('OK');
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
運行效果如下:
這樣就可以直接修復掉線上bug了,不需要等待
App Store
的審核。