I'm having some troubles when my app receives multiple JSON objects at the same time. I'm using a TCP socket that is open to my server which sends me messages. The reason i seem to recieve multiple messages is probably due to network lag.
This is what a server message can look like (i then put this into a NSString and try to parse the JSON):
{
"id": "156806",
"type": "message",
"userCity": "",
"userCountry": "",
"os": "",
"browser": "",
"trafficType": "",
"seKeyword": "",
"seType": "",
"currentPage": "",
"userId": "1",
"agentId": "352",
"customField1": "",
"visitorNick": "Visitor 147220060",
"msg": "asd",
"time": "16:05",
"channel": "V147220060",
"visits": "254"
} {
"type": "previewStopped",
"msg": "",
"visitorNick": "Mackan",
"customField1": "",
"visitorNick": "Visitor V147220060",
"time": "16:05",
"channel": "V147220060"
} {
"id": "156807",
"type": "message",
"userCity": "",
"userCountry": "",
"os": "",
"browser": "",
"trafficType": "",
"seKeyword": "",
"seType": "",
"currentPage": "",
"userId": "1",
"agentId": "352",
"customField1": "",
"visitorNick": "Visitor 147220060",
"msg": "as",
"time": "16:05",
"channel": "V147220060",
"visits": "254"
} {
"id": "156808",
"type": "message",
"userCity": "",
"userCountry": "",
"os": "",
"browser": "",
"trafficType": "",
"seKeyword": "",
"seType": "",
"currentPage": "",
"userId": "1",
"agentId": "352",
"customField1": "",
"visitorNick": "Visitor 147220060",
"msg": "da",
"time": "16:05",
"channel": "V147220060",
"visits": "254"
}
And here is how i currently parse the NSString, note that the above JSON is outputData in the code below:
// Parse the message from the server
NSError* error;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [outputData dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
NSString* type = [JSON objectForKey:@"type"];
if(error) {
NSLog(@"PARSE ERROR ------------->>>>> : %@\n", error);
}
NSLog(@"SERVER TYPE --> %@\n", type);
if([type isEqualToString:@"message"]) {
[self messageReceived:outputData];
}
The above works perfectly when i only recieve one JSON in outputData but when multiple JSONs are recieved it trows an error:
PARSE ERROR ------------->>>>> : Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x14e9acb0 {NSDebugDescription=Garbage at end.}
Any ideas how to handle this?
[outputData dataUsingEncoding:NSUTF8StringEncoding]?NSJSONReadingMutableContainerstoNSJSONReadingAllowFragments