The NSURLConnectionDidFinishLoading connection is called before the entire file is loaded.

I am using NSURLConnection to download an archived file from a web service. In didReceiveData, I am adding data to a file and using a good internet connection, everything works correctly. The file will be unpacked at boot. If, however, I have a poor internet connection, the connectionDidFinishLoading connection will be called before all data has been received. Is there another delegate method that needs to be captured or some kind of timeout in NSURLConnection that makes it think that the download is finished, rather than calling didFailWithError?

+3
source share
2 answers

You must ensure that the size of the data received is as expected.

:

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

, didReceiveData, dataSize, connectionDidFinishLoading, dataSize 0, .

+4

, , , , .

-, ( iOS), [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:TRUE];

, , , - :

- (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 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];}

,

0

Source: https://habr.com/ru/post/1761251/