Downloading large files with AFNetworking

2019-03-14 07:34发布

I'm trying to implement downloading of a large file and show to user current progress, but block in:

-[AFURLConnectionOperation setDownloadProgressBlock:] 

returns incorrect bytesRead and totalBytesRead values (they are smaller than they should be).

For example: If I have a 90MB file and when it downloads completely, latest block invocation in setDownloadProgressBlock: gives me totalBytesRead value about 30MB. On other side, if file is 2MB large, latest block invocation gives correct totalBytesRead 2MB value.

AFNetworking is updated to the latest version from github.
If AFNetworking can't do it correctly, what solution can I use?

Edit: I've determined that even if file is not downloaded completely (and this happens every time with relatively big file) AFNetworking calls success block in:

-[AFHTTPRequestOperation setCompletionBlockWithSuccess:failure:]

I asked a similar question here about this situation, but didn't get any answers.
I can check in code downloaded and real file sizes, but AFNetworking has no API for continuation of partial download.

2条回答
smile是对你的礼貌
2楼-- · 2019-03-14 08:27

phix23 answered to my initial question, so there is really no problem with progress block. I'm answering to my edit.

When success block in

-[AFHTTPRequestOperation setCompletionBlockWithSuccess:failure:]

is called, I can compare the number of bytes downloaded with the number of bytes expected to download (it is not very hard to implement in code). If the number of downloaded bytes is smaller - I can continue file download from place where it was interrupted. To do this, I'm using Range http header in NSURLRequest, here is more information:
Continue an interrupted download on iPhone
How to implement resumable file downloads on iPhone SDK

So, the problem is not really with AFNetworking (NSURLConnection has same behavior), but, I think, developers of the framework could take into account this situation.

查看更多
做个烂人
3楼-- · 2019-03-14 08:28

I have no problems with the setDownloadProgressBlock in AFNetworking.

The wiki explains how to track download progress: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ

For progress tracking you don't need the bytesRead (number of bytes written in a particular callback).

Example code:

[downloadoperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float progress = ((float)totalBytesRead) / totalBytesExpectedToRead;
        self.progressView.progress = progress;
    }];
查看更多
登录 后发表回答