作用
iOS熱更新、熱修復、熱重載、動態創建類、新增方法、擴展新界面。
體驗
下載的demo工程,cd到JS目錄下,運行運行 npm run build
,這條命令會將剛剛修改的工作區代碼(src
)經過轉義壓縮輸出到outputs
目錄下, outputs
目錄下的文件供app讀取使用.
使用
需要一些JS相關的支持,要確保本機已安裝npm.如果不知道的同學可以百度安裝。 如果已經安裝好npm可以往下操作
1.cd /demo/JS
執行 npm install
2.npm run server
關于build說明
- 執行
npm run build
將文件轉成各自對應的js. - 執行
npm run package
將src目錄下文件打包成一個文件.(demo中使用此種方式進行演示).
熱重載
無論動態創建類或原生類都需要繼承自Root控制器或者接收通知實現重載方法
JS例子
defineClass('LHBUGController:LHJSRootController', {
viewDidLoad: function () {
Super().viewDidLoad();
},
}, {
});
OC例子
@implementation AppDelegate
- (void)updateResource:(NSString *)filename callbacl:(void(^)(void))callback {
NSURLSession *session = [NSURLSession sharedSession];
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@/%@",
[LHHotRefrshTool shareInstance].getLocaServerIP,
[LHHotRefrshTool shareInstance].getLocaServerPort,
filename]]];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!data || error) {
// 本地代理未開啟,加載本地bundle資源,無法實時預覽
NSString *srcPath = [[NSBundle mainBundle] pathForResource:@"hotfixPatch" ofType:@"js"];
NSString *jsCode = [[NSString alloc] initWithData:[[NSFileManager defaultManager] contentsAtPath:srcPath] encoding:NSUTF8StringEncoding];
[[TTPatch shareInstance] evaluateScript:jsCode withSourceURL:[NSURL URLWithString:@"hotfixPatch.js"]];
return;
}
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (!result || !result.length) {
return ;
}
[[TTPatch shareInstance] evaluateScript:result withSourceURL:[NSURL URLWithString:filename]];
dispatch_async(dispatch_get_main_queue(), ^{
/// 發送熱重載通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"LHJSNotificationRefresh" object:nil];
});
if (callback) {
callback();
}
}];
[dataTask resume];
}
#pragma mark - LHHotRefrshTool代理
- (void)reviceRefresh:(id)msg {
[self updateResource:msg callbacl:nil];
}
@end
@implementation LHJSRootController
- (void)viewDidLoad {
[super viewDidLoad];
/// 監聽通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:@"LHJSNotificationRefresh" object:nil];
}
/// 刷新實現
- (void)refresh {
}
@end