进度跟踪问题 - AFNetworking队列

时间:2013-09-27 12:55:28

标签: iphone ios objective-c afnetworking

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

问题是我为每个请求分别进行了进展。但是我要求两个请求的整体进展。

1 个答案:

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

希望这有帮助:)