Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

totalBytesExpectedToRead in setDownloadProgressBlock remains -1 until download is done

I have been googling to no avail, and hope for your help on this.

I tried to download an image using AFHTTPRequestOperation streaming (by setting outputstream). It downloads the file, no problem. But the progress bar wont display correct, because totalBytesExpectedToRead always returns -1, and only returns the correct value when download is complete.

Is this the nature of streaming? Or did I do something wrong?

My code below.

Thanks in advance!

(void)invokeAsynchronousSTREAMING:(NSString*)path locationToSave:(NSString*)locationToSave parameters:(NSDictionary*)paramDict callId:(NSString*)callId {

NSMutableURLRequest *request = [[AFServerAPIClient sharedClient] requestWithMethod:@"GET" 
                                                                              path:path 
                                                                        parameters:paramDict];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

if(locationToSave!=nil) {
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:locationToSave append:NO];
}

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)  {

   //DO SOMETHING

} 
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //DO SOMETHING
    }
 ];

[operation setDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

    NSLog(@"invokeAsyncronousSTREAMING - Received %lld of %lld bytes", totalBytesRead, totalBytesExpectedToRead);

    //DO SOMETHING
}];

[operation start];

}//end invokeAsyncStreaming

like image 446
Eve Avatar asked Oct 24 '12 04:10

Eve


2 Answers

Download progress may return -1 if the server does not set the Content-Length HTTP header in the response.

In this case, it is recommended that you use an indeterminate progress indicator instead.

like image 200
mattt Avatar answered Nov 09 '22 21:11

mattt


Also, as per this question, if gzip compression is used during the transfer, totalBytesExpectedToRead will still return -1 even if the header does contain a Content-Length (both cases being quite frequent). This is because the contents can only be uncompressed at the end of the transfer, hence its size won't be known before the transfer completes.

like image 27
lucianf Avatar answered Nov 09 '22 20:11

lucianf