【发布时间】:2014-09-07 13:57:16
【问题描述】:
我想下载多个文件,然后向用户显示总进度。
但问题就在这里,我不知道我应该如何计算总进度。
这是我的工作: 首先我得到了预计从所有文件中接收的总字节数:
for (NSURL candidateUrl in UrlsList)
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:candidateURL];
//setting HTTPMethod of request from GET to HEAD to download header files of requests, so we can get file size before downloaing file
[request setHTTPMethod:@"HEAD"];
getTotalImagesBytesOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[getTotalImagesBytesOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
//setting totalImagesBytesExpectedToRead of all images. we use it to know how many bytes we should download for all the images
totalImagesBytesExpectedToRead += [operation.response expectedContentLength];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[operationQueue addOperation:getTotalImagesBytesOperation];
}
估计总文件大小后:
//downloading images
for (NSURL *imageUrl in imagesURLList) {
NSURLRequest *request = [NSURLRequest requestWithURL:imageUrl];
AFImageRequestOperation *downloadImageOperation = [AFImageRequestOperation imageRequestOperationWithRequest:request
imageProcessingBlock:nil
success: ^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
NSLog(@"success")
}
failure: ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"%@", [error localizedDescription]);
}];
[operationQueue addOperation:downloadImageOperation];
[downloadImageOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
{
**HOW TO CALCULATE TOTAL PROGRESS**
}
我不知道如何计算总大小! 我们拥有的价值观: 以上方法为您提供的当前文件的 totalBytesOfAllTheFiles、totalBytesRead 和 totalBytesExpectedToRead、indexOfCurrentFile 和 countOfFiles。
小心 setDownloadProgressBlock 调用数百次。
有人知道吗? (抱歉代码格式错误!)
【问题讨论】:
-
你不把
totalBytesRead除以totalBytesExpectedToRead吗? -
@evan.stoddard
totalBytesRead/totalBytesExpectedToRead给了我当前文件的完成百分比。不是整个文件! -
首先考虑:你真的需要如此精确才能使用总字节数来计算进度吗?我使用“下载的总文件数”/“要下载的总文件数”来计算应用程序的进度。这要容易得多。
-
想一想您的前五个文件的总大小为 1 mb,而后五个文件的大小为 100 mb。这个计算不好。
-
在这种情况下,唯一的方法可能是在下载开始之前从网络某处的数据文件中读取“总大小”信息。如果这不可能,您必须重新考虑您的应用程序设计。在下载文件之前,您无法知道所有文件的大小。
标签: ios objective-c download afnetworking