关于进度,请参见setDownloadProgressBlock(AFURLConnectionOperation 的一部分,AFHTTPRequestOperation 是其中的子类),例如:
[operation setDownloadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
NSLog(@"Sent %d of %d bytes, %@", totalBytesWritten, totalBytesExpectedToWrite, path);
}];
并且,在您的代码示例中,您正在调用setCompletionBlockWithSuccess:failure:,以便提供有关各个操作完成的状态。就个人而言,在我的小测试中,我只维护了一组我请求的下载,并让这三个块(进度、成功和失败)更新我的下载状态代码,如下所示:
for (NSInteger i = 0; i < 20; i++)
{
NSURLRequest *request = ... // set the request accordingly
// create a download object to keep track of the status of my download
DownloadObject *object = [[DownloadObject alloc] init];
download.title = [NSString stringWithFormat:@"Download %d", i];
download.status = kDownloadObjectStatusNotStarted;
[self.downloadObjects addObject:download];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
download.status = kDownloadObjectStatusDoneSucceeded;
// update my UI, for example, I have table view with one row per download
//
// [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]
// withRowAnimation:UITableViewRowAnimationNone];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
download.status = kDownloadObjectStatusDoneFailed;
// update UI
//
// [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]
// withRowAnimation:UITableViewRowAnimationNone];
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
download.totalBytesRead = totalBytesRead;
download.status = kDownloadObjectStatusInProgress;
// update UI
//
// [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]
// withRowAnimation:UITableViewRowAnimationNone];
}];
[queue addOperation:operation];
}
您可以通过这种方式跟踪各个下载。您也可以只跟踪待处理的操作(或查询HTTPClient 对象的operationQueue 属性,然后查看其operationCount 属性)。
在下载100个文件方面,有两个考虑:
-
我原以为您想在您的 HTTPClient 子类的 operationQueue 上调用 setMaxConcurrentOperationCount,将其设置为某个合理的数字(4 或 5),就像浏览 AFNetworking 代码一样,它似乎没有这样做。我发现如果你超出这个范围,回报就会递减,并且如果所有文件都来自单个服务器,那么在给定客户端和给定服务器之间可以执行多少并发操作是有限制的。
我读过传闻称 Apple 将拒绝通过蜂窝网络发出特殊请求的应用程序。见https://stackoverflow.com/a/14922807/1271826。