IOS JSON Error: NSDebugDescription = Trash at the end
This is a very strange error when grabbing JSON from my server (which is generated via PHP), I get this error when calling:
json = [NSJSONSerialization JSONObjectWithData:kivaData
options:kNilOptions
error:&jsonError];
JSON Error: Error Domain = NSCocoaErrorDomain Code = 3840 "Operation could not be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo = 0x178467d00 {NSDebugDescription = Garbage at end.}
My (NSData * kivaData) parses great, but it can't parse JSON.
I ran my JSON code at http://jsonlint.com/ and it exits every time in action.
This is really weird because it can parse JSON when I connect to Wi-Fi, but when I try to do it over my cellular it doesn't work. He works on cell phones for some nations, but every time.
source to share
coding is very important. If your json is valid, the problem might be that you have special characters in your json data that are not properly handled by the json serializer. When submitting data, make sure you have the correct url encoding when submitting content so that the client parses it correctly. Use utf-8 always or base64.
source to share
JsonData is usually stored in dictionary format. Since json cannot parse continuous data [its inability to separate responses] it is throwing this error.
You can maintain a dictionary to store the responses received from the server. Each challenge will have a unique answer. Therefore, create a dictionary with "keys" as "taskIdentifier" of tasks and "values" as "data".
For example: Inside didReceiveData or any other equivalent methods [where you get the response from the server] store the response in a dictionary using the taskIdentifier as keys.
NSString *taskID = [@(dataTask.taskIdentifier) stringValue];
[_task_data_dictionary setObject:data forKey:taskID];
Here _task_data_dictionary is a dictionary. This way you can get rid of the above error.
After that you can get the data using the same dictionary using this code
NSData *data = [_task_data_dictionary objectForKey:taskNumber];
again with taskIdentifier.
Hope it helps.
source to share
using swift 4, first of all check the JSON data using print:
print (String(data:data!, encoding: .utf8)!)
check for spaces or unwanted characters, then remove them:
var string = String(data: data!, encoding: .utf8)
string = string?.replacingOccurrences(of: "/r/n", with: "")
after that assign the string back to the data variable:
let data1 = string!.data(using: .utf8)
source to share