Stephen Groom
Stephen Groom

Reputation: 3997

NSURLConnection sendAsynchronousRequest and NSURLConnection initWithRequest return different data

I was using [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {}] to return some XML data but the files got so big that a simple UIActivityIndicator wasn't the best idea any more. I moved to [[NSURLConnection alloc] initWithRequest: delegate: so that I could keep track of the progress and use a UIProgressView instead

I am having problems now with the new delegate code returning data before the end of the file resulting in this error from GDataXML Entity: line 85: parser error : Premature end of data in tag text line 85 igured to accept a range of values, and up to a certain number of decimal places

If I run

[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSLog(@"%i", [data length]);
}];

It writes to console: 17514

When I instead run

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];

I get a different length response. My Delegate method is:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"%i", [data length]);
}

3802 is printed to the console followed by 13712

Does anybody know what is going wrong here?

Thanks Stephen

Upvotes: 0

Views: 949

Answers (1)

Carl Veazey
Carl Veazey

Reputation: 18363

In connection:didReceiveData: you must append the result to an NSMutableData instance to collect the entire response. From the NSURLConnectionDelegate docs, regarding the data parameter for this method:

The newly available data. The delegate should concatenate the contents of each data object delivered to build up the complete data for a URL load.

As an example:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.mutableResponseData appendData:data];
}

Once the connection has finished loading the data, parse the data, e.g.:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   [self parse:self.mutableResponseData];
}

Upvotes: 3

Related Questions