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

问题

具体代码:

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


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豪冷啊

你的鼓励是对我的认可!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值