JSPatch能够通过使用javaScript调用iOS原生接口的方法实现iOS应用的热更新。(JSPatch实现原理)
下面介绍JSPath的使用方法:
1、从GitHub上下载JSPath的源码,将JSPatch文件夹拉入工程(包括JSEngine.h、JSEngine.m、JSPatch.js三个文件),添加javascriptcore.framework
2、引入JPEngine.h头文件,通过服务器获取JavaScript文件后执行[JPEngine evalueateScript:@“js代码”]即可实现iOS代码的热更新。
appdelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//自定义的js更新类(根据需要来修改调用时机,如可以在每次程序为active状态时调用)
[JspatchManager jsUpdate];
self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
self.window.backgroundColor = [UIColor whiteColor];
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[NotificationTimeList new]];
[self.window makeKeyAndVisible];
return YES;
}
jsManager
/**
更新本地js文件并执行
*/
+ (void)jsUpdate{
//app从本地获取app版本号和js文件版本号作为参数进行请求,服务器返回对应的js脚本文件、版本号(多个文件合并成一个)
NSString *jsUrl = @"http://www.jspatchserver.com/SolveReduplicateData.js";
NSString *appVersion = [self appVersion];
NSString *jsLocalVersion = [self jsLocalVersion];
NSDictionary *parameters = @{@"appVersion":appVersion, @"jsVersion":jsLocalVersion};
NSLog(@"parameters = %@",parameters);
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:jsUrl]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *jsString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *jsServerVersion = @"";
//测试使用
jsServerVersion = [NSString stringWithFormat:@"%@1",jsLocalVersion];
if (connectionError) {
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"js"];
jsString = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil];
}
NSLog(@"jsServerVersion = %@",jsServerVersion);
NSLog(@"jsLocalVersion = %@",jsLocalVersion);
NSLog(@"jsstring = %@",jsString);
//如果版本号不同则进行处理
if (![jsLocalVersion isEqualToString:jsServerVersion]) {
[[NSUserDefaults standardUserDefaults] setObject:jsServerVersion forKey:kJSPatchVersion];
//保存js文件到本地
[self saveJsToLocal:jsString];
//解密js文件
NSString *decodedJs = [self decodeJs:jsString];
//使用js文件
[JPEngine evaluateScript:decodedJs];
}
}];
}
js代码
defineClass('NotificationTimeList',{
dataSet_hasModel:function(dataSet,model){
console.log("js frome local server")
for (var i=0; i
注意
1、服务器需要维护一个列表,记录app版本和js版本的对应关系,应用程序使用本地app版本号和js版本号作为请求参数,服务器根据对应关系列表返回正确的js文件和版本号即可。
2、服务器端上传js文件后需要更新对应关系列表,如果js文件有多个生成单一的js文件使用会更方便。
3、如果使用mamp在本地搭建服务器,使用http协议,需要修改info.plist文件,并且需要使用模拟器运行程序
4、js文件内容一定要经过加密处理(demo中没有实现)
5、jspatch提供了下发js文件的平台http://jspatch.com
jspatch语法
1、property属性使用set/get调用
2、带下划线的方法jspatch中使用双下划线
3、for循环使用简单的形式,不要使用for( id obj in models ){ }形式
4、在对字符串或者数组、字典操作的时候应该转成js的格式
var MonthAndYear = self.currentYearString().toJS() + '年' + self.currentMonthString().toJS() + '月';
5、js方法之间是用“,”分割的