NSURLConnection DidReceiveData Calls Twice

May 17, 2013

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:

@property (strong, nonatomic) NSMutableData *receivedData;

@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.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive