NSURLConnection DidReceiveData Calls Twice
Let’s say you are making calls to an API and it delivers a lot of information to you all at once. Chances are if you’re putting out the data directly from the
– (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
function it will give you a null, because your JSON string won’t validate. The fix for this is relatively simple if you are aware of the other function you will need.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
This is what you can use to piece together the data that the connection receives. In the end, you want it to look like this:
#ViewController.h
@property (strong, nonatomic) NSMutableData *receivedData;
#ViewController.m
@synthesize receivedData;
//... call to server
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
{
if (!receivedData)
{
receivedData = [NSMutableData data];
}
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:nil];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:dictionary forKey:@"tableContents"];
receivedData = nil;
[self.myTableView reloadData];
}
Key here is that the data must be appended. If you intend to load the view again when you return from a detail view, you will need to set the receivedData to nil after storing the contents into the NSDictionary. Then you will also want to make sure the table data reloads after the connection finishes receiving all the data. This will ensure a fully populated list within a second of the table loading.