1. 程式人生 > >iOS WKWebView呼叫JS事件時丟擲的Error

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