I thought I would share a little detail that burned me this week. I'm working on a new project that integrates with Twitter to pull data down from the JSON Search API. There are a ton of tutorials out there that describe how to use the JSON Framework to parse a JSON resultset with iOS, although one thing I noticed with all the tutorials, is that they are doing this Wrong!
A good example is the tutorial from IOS Developer Tips this is actually a really great tutorial for the most part, but there is one error, that leads to epic failure.
The failure occurs with the usage of
- (void)connection:(NSURLConnection *)connection
which is the method they are using to act on the JSON results. When I tried to implement this with the Twitter search api, it would sometimes work, and sometimes fail. It was completely random and driving me insane. I would receive these horrid errors from the JSON parser...
"Error Domain=org.brautaset.JSON.ErrorDomain Code=5 \
"Unescaped control character '0x0'\"
This is the worst kind of error because it works sometimes, and fails miserably in others and none of the debug output is really helpful at all.
Now the reason why this fails is due to the nature of the Asynchronous request setup using NSURLConnection previously in this example. This will result in the didReceiveData method *possibly* being called multiple times as the data is delivered. Meaning sometimes I would get a whole JSON data string that the parser could parse fine, but sometimes I would end up attempting to parse the fragments of the JSON string that had been downloaded so far, thus resulting in failure.
The right way to implement this is to create an NSMutableData object and when the didReceiveData method is called, append the result data to the NSMutableData object. Then utilize the connectionDidFinish method of NSURLConnection, to parse the resulting and now complete dataset.
Special thanks to @SteveStreza for the guidance on this one...