問題
具體代碼:
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表達式。