iOS WKWebView调用JS事件时抛出的Error

2019-05-31  本文已影响0人  豪冷

问题

具体代码:

NSString *api = [URL.absoluteString stringByRemovingPercentEncoding];
NSString *result = [NSString jh_JSONStringFromDictionary:responseObject];
NSString *method = [NSString stringWithFormat:@"callJSMethod('%@','%@')",api,result];
[vc.webView evaluateJavaScript:method completionHandler:^(id _Nullable result, NSError * _Nullable error) {
    NSLog(@"result:%@,error:%@",result,error);
}];

报错:

Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={NSLocalizedDescription=A JavaScript exception occurred

JS接收到的 result显示的是 [object Object]
并不是字符串
明明转成了字符串的啊!


发现

在 dic 转 string 时

NSDictionary *dic = @{@"name":@"haocold"};
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"string1:%@",string);

输入的结果是:

{
  "name" : "haocold"
}

转换用的 options 是 NSJSONWritingPrettyPrinted


解决

转换用的 options 使用 kNilOptions

NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:nil];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"string2:%@",string);

输入的结果是:

{"name":"haocold"}

两者在格式上有明显的区别,难怪 JS 识别不了!

延伸

关于 NSJSONWritingPrettyPrinted的官方描述:

The writing option that uses white space and indentation to make the output more readable.
If this option is not set, the most compact possible JSON representation is generated.

翻译:

这个写入选项会使用空格和缩进来使输出更有可读性。
如果这个选项没有设置,则生成紧凑合理的JSON表达式。

链式语法自动布局库

https://github.com/xjh093/JHFrameLayout


我 的 github:https://github.com/xjh093


上一篇下一篇

猜你喜欢

热点阅读