概述
一說到熱修復,可能很多人會覺得應該很復雜,很難用(我以前是這么覺得的。。。),實際使用起來蠻簡單的,這里以一個小demo演示熱修復是如何修復崩潰的,具體更深入的用法,可以看這個
https://github.com/bang590/JSPatch/wiki/JSPatch-%E5%9F%BA%E7%A1%80%E7%94%A8%E6%B3%95
實現原理:https://github.com/bang590/JSPatch/wiki/JSPatch-實現原理詳解
使用
1.下載SDK
打開JSPatch網站,下載SDK:http://jspatch.com/Index/sdk
2.導入依賴庫
新建一個項目,名為JSPatchDemo,將下載后的JavaScriptCore.framework文件拖到項目中,並導入libz.dylib(或libz.tbd) 和 JavaScriptCore.framework
在AppDelegate里配置,startWithAppKey需要配上自己的Key,在第三步會詳細介紹。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. [JSPatch startWithAppKey:@"你的APPKey"]; //用來檢測回調的狀態,是更新或者是執行腳本之類的,相關信息,會打印在你的控制台 [JSPatch setupCallback:^(JPCallbackType type, NSDictionary *data, NSError *error) { }]; [JSPatch setupDevelopment]; [JSPatch sync]; return YES; }
在ViewController里寫上一個方法為jsPatchTest,用於改變文本的文字。
#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UILabel *label; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; _label = [[UILabel alloc] init]; _label.font = [UIFont systemFontOfSize:14]; _label.frame = CGRectMake(50, 100, 150, 50); _label.backgroundColor = [UIColor yellowColor]; [self.view addSubview:_label]; [self jsPatchTest]; } - (void)jsPatchTest { self.label.text = @"哈哈哈哈哈哈"; } @end
3、獲取AppKey並發布
打開JSPatch官網點擊左上角注冊 -> http://www.jspatch.com/
點新增APP,隨便填寫APP名,如:
將AppKey填寫到AppDelegate--StartWithAppKey中
點擊添加版本,填寫和工程目錄的一致,如1.0
創建一個main.js文件並在里面寫上以下代碼
defineClass('ViewController', { jsPatchTest : function() { self.label().setText("label的text被改掉了"); }, })
發布補丁
再次重新打開app,你會發現,會報http的錯。。。在info.plist里加上如下代碼,允許http訪問
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
總結
總體使用還是比較簡單的,更多功能可以去文檔中發掘
補充
1、可能很多人都不會寫js補丁,好在JSPatch作者還為我們准備了另一個工具。
http://bang590.github.io/JSPatchConvertor/
這個工具可以幫助我們轉換OC代碼為JS
2、JS一定要加密,下面是方法截圖和文檔:
文檔:http://jspatch.com/Docs/rsa