用用JavaScriptCore,来解决实际问题
Demo url encodeURIComponent
@import JavaScriptCore;
NSString *scene = webUrl;
JSContext *context = [[JSContext alloc] init];
JSValue *encodeValue = [context evaluateScript:[NSString stringWithFormat:@"encodeURIComponent('%@');", scene]];
if (encodeValue.isString) {
scene = encodeValue.toString;
}
一般接口都是返回json格式的字符串。
但--------有个特殊的接口返回了js代码,在js里面是我们要用的json。
json_parse({"code":200,"data":{"base64Str":"YmFzZTY0U3Ry"},"msg":"Request Success!"})
遇到这种情况 最好跟接口商量,看能不能加个参数来控制下返回接口。
最好直接返回json
如果接口不改的话,有两种解决方式
一、字符串截取
NSString *callback = @"json_parse";
NSString *json = [[res substringToIndex:res.length - 1] substringFromIndex:callback.length + 1];
这种方便直接又方便,比较简单
二、用JavaScriptCore执行js代码来获取
既然接口返回但是js代码,就可以用JavaScriptCore执行。
接口只返回了方法调用,没有方法实现怎么办? 注入一个
模拟接口返回的数据。注意需要转义
NSString *res = @"json_parse({\"code\":200,\"data\":{\"base64Str\":\"YmFzZTY0U3Ry\"},\"msg\":\"Request Success!\"})";
建立JS运行环境
JSContext *context = [[JSContext alloc] init];
设置异常捕获方法
context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
NSLog(@"JS Error: %@", exception);
};
注入js同名方法json_parse
[context evaluateScript:@"function json_parse(jsonstring) {return JSON.stringify(jsonstring, null, 4);}"];
用js环境执行返回的js代码。接口只返回了方法调用,方法的实现就是上一步注入的
JSValue *value = [context evaluateScript:res];
判断执行结果,并解析
if (value.isString) {
NSString *toStr = value.toString;
if (toStr) {
NSData *data = [toStr dataUsingEncoding:NSUTF8StringEncoding];
// json解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", dic);
}
}
总结
第二种方法比较麻烦,但有助于拓展思路,以后遇到类似问题多一种解决办法