天天看点

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"      

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

链式语法自动布局库

​​https://github.com/xjh093/JHFrameLayout​​

继续阅读