我有以下代码用于使用AFNetwork队列下载两个请求
NSMutableArray *operations = [NSMutableArray array];
NSURLRequest *request1 = [NSURLRequest requestWithURL:URL1];
AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
operation1.outputStream = [NSOutputStream outputStreamToFileAtPath:PATH1 append:NO];
[operation1 setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
float progress = (float)totalBytesRead / totalBytesExpectedToRead;
NSLog(@"Progress 1 = %f",progress);
}];
[operations addObject:operation1];
NSURLRequest *request2 = [NSURLRequest requestWithURL:URL2];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request2];
operation2.outputStream = [NSOutputStream outputStreamToFileAtPath:PATH2 append:NO];
[operation2 setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
float progress = (float)totalBytesRead / totalBytesExpectedToRead;
NSLog(@"Progress 2 = %f",progress*100);
}];
[operations addObject:operation2];
向AFTHTTPClient
AFHTTPClient *requestHandler = [[AFHTTPClient alloc] initWithBaseURL:BASEURL];
[requestHandler enqueueBatchOfHTTPRequestOperations:operations progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations) {
NSLog(@"%d completed on %d",numberOfCompletedOperations,totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
}];
问题是我为每个请求分别进行了进展。但是我要求两个请求的整体进展。
答案 0 :(得分:1)
只需创建一个全局浮动来控制它,所有进度的总和是:
TotalProgress = firstProgress / numOperations + secondProgress / numOperations
//Declare this like a global.
#define numOperation 2
float globalProgress = 0.0f;
//Your Operation Instances:
NSMutableArray *operations = [NSMutableArray array];
NSURLRequest *request1 = [NSURLRequest requestWithURL:URL1];
AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
operation1.outputStream = [NSOutputStream outputStreamToFileAtPath:PATH1 append:NO];
[operation1 setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
globalProgress += ((float)totalBytesRead / totalBytesExpectedToRead)/numOperation;
}];
[operations addObject:operation1];
NSURLRequest *request2 = [NSURLRequest requestWithURL:URL2];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request2];
operation2.outputStream = [NSOutputStream outputStreamToFileAtPath:PATH2 append:NO];
[operation2 setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
globalProgress += ((float)totalBytesRead / totalBytesExpectedToRead)/numOperation;
}];
[operations addObject:operation2];
希望这有帮助:)