2

我有以下代码用于使用 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) {
}];

问题是我为每个请求单独获取进度。但我需要两个请求的整体进展。

4

1 回答 1

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];

希望这有帮助:)

于 2013-09-27T14:50:17.097 回答