前言
项目中目前实现了通过动态下载资源包来替换widget皮肤的功能,资源包中包括js代码文件和资源图片. js文件编写比较简单,简单初始化了对象,并把布局信息写入对象中, 客户端解析js成数据model,根据数据model展示布局.
这样做的好处首先替换widget皮肤不用发版,其次上新皮肤的时候只需要客户端开发人员拿到资源图片之后编写js文件就可以实现布局,服务端只需要提供上传和下载资源包的接口,不用每次更新widget都在接口中下发布局信息.
简单贴部分代码
test.js代码
var viewJson = function() {
//定义输出对象
var resultWidget = new Object();
resultWidget.widget_type = 1;
resultWidget.background_type = 1;
resultWidget.width = 320;
resultWidget.height = 500;
resultWidget.imageName = "widget_bg.png"
var testItem1 = new Object();
testItem1.id = 1;
testItem1.name = "item1";
testItem1.imageName = "item1.png";
var testItem2 = new Object();
testItem2.id = 2;
testItem2.name = "item2";
testItem2.imageName = "item2.png";
resultWidget.Items = [testItem1, testItem2];
return JSON.stringify(resultWidget);
};
swift代码:
//获取js文件路径
let jsPathString = "TempFiles/test.js"
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let fileURL = dir?.appendingPathComponent(jsPathString)
//创建JSContext对象
var jsContext = JSContext.init();
do {
//读取js代码
let jsString = try String(contentsOf: fileURL!, encoding: .utf8)
//解析JS代码
_ = jsContext?.evaluateScript(jsString)
//根据js变量名,获取viewJson字段
let result = jsContext?.objectForKeyedSubscript("viewJson")
let resultJson = result?.call(withArguments: nil).toString()
let resultData = resultJson?.data(using: .utf8)
//转换为字典格式
let resultDict = try JSONSerialization.jsonObject(with: resultData!, options: .allowFragments) as? Dictionary<String, Any>
print(resultDict ?? 0);
}
catch {
}
OC代码:
JSContext *context = [[JSContext alloc]init];
NSString *js = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:nil];
[context evaluateScript:js];
//根据js变量名,获取viewJson字段
JSValue *jsValue = context[@"viewJson"];
JSValue *loadingJson = [jsValue callWithArguments:nil];
NSString *resultJson = [loadingJson toString];
NSData *jsonData = [resultJson dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@", dic);