Russ
Russ

Reputation: 124

NSURLConnection connectionDidFinishLoading called before all file is downloaded

I am using NSURLConnection to download a zipped file from a web service. In the didReceiveData I append the data to a file and using a good internet connection all appears to work correctly. The file is transparently unzipped as it is downloaded. If, however, I have a poor internet connection the connectionDidFinishLoading appears to be called before all the data has been received. Is there another delegate method that I should be trapping or some kind of timeout in NSURLConnection that is making it think that the download is finished as opposed to calling didFailWithError?

Upvotes: 3

Views: 1875

Answers (2)

user1458963
user1458963

Reputation: 181

I'm back on this issue because I had it too and passed a lot of time to understand what's wrong.

Apparently, I have better result (on iOS) when I use [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:TRUE];

I did a double check on the received data and relaunch the request where it stopped if didn't received all the data, with something like:

- (void)connectionDidFinishLoading:(NSURLConnection *)myConnection{ if (receivedDataSize<expectedDataSize) // protection { [self.connection cancel]; [self setConnection:nil]; [self setResponseData:nil];
self.connection = [NSURLConnection connectionWithRequest:[myConnection originalRequest] delegate:self];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:myConnection.originalRequest.URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRestRequestTimeout]; [request setHTTPMethod:myConnection.originalRequest.HTTPMethod];

    // Define the bytes we wish to download. Start from where it's stopped
    NSString *range = [NSString stringWithFormat:@"bytes=%i-",[[NSNumber numberWithLongLong:receivedDataSize]intValue]];
    [request setValue:range forHTTPHeaderField:@"Range"];
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:TRUE];}

Hope it can help

Upvotes: 0

Guy Ephraim
Guy Ephraim

Reputation: 3520

you should check that the size of the received data is as expected.

the following will get you the expected size of data:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
 long long dataSize = [response expectedContentLength];
}

every time you get a call to didReceiveData, reduce it from the dataSize, and if you get a call to connectionDidFinishLoading and the dataSize is bigger than 0, there is a problem.

Upvotes: 4

Related Questions