totalBytesExpectedToRead in setDownloadProgressBlo

2020-03-03 05:17发布

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

2条回答
叼着烟拽天下
2楼-- · 2020-03-03 05:48

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.

查看更多
▲ chillily
3楼-- · 2020-03-03 05:49

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.

查看更多
登录 后发表回答