从ASIHTTPRequest切换到AFNetworking - ASINetworkQueue的问题

7
我正在解决一个问题,需要按照队列下载大约10个不同的大文件,并显示进度条来指示总传输状态。我已经使用iOS4中的ASIHTTPRequest完美实现了这一点,但是由于ASIHTTPRequest在iOS5上存在问题且不再维护,所以我尝试转换到AFNetworking。
我知道可以使用AFHTTPRequestOperation的downloadProgressBlock报告单个请求的进度,但是我似乎找不到一种方法来报告在同一个NSOperationQueue上执行的多个请求的总体进度。
有什么建议吗?谢谢!
3个回答

1
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];

操作为 AFHTTPRequestOperation


0
我会尝试使用UIProgressView的子类来跟踪您正在观察的所有不同项目,并具有将它们的进度相加的逻辑。代码可能如下所示:
 @implementation customUIProgressView

-(void) updateItem:(int) itemNum ToPercent:(NSNumber *) percentDoneOnItem {
  [self.progressQueue  itemAtIndexPath:itemNum] = percentDoneOnItem;

  [self updateProgress];
}
-(void) updateProgress {
  float tempProgress = 0;
  for (int i=1; i <= [self.progressQueue count]; i++) {
    tempProgress += [[self.progressQueue  itemAtIndexPath:itemNum] floatValue];
  }
  self.progress = tempProgress / [self.progressQueue count];
}

这是MVC设计模式的不良编码实践。 - Alex Zielenski
也许。对于动态大小的内容来说,它是完成工作的正确工具。它可以准确地显示进度,而无需先知道内容的大小。查找大型文件(如视频或照片)的大小可能是一项昂贵的操作。 - clreina

0
你可以通过继承AFURLConnectionOperation类来添加两个新属性:(NSInteger)totalBytesSent(NSInteger)totalBytesExpectedToSend。你应该在NSURLConnection的回调方法中设置这些属性,像这样:
- (void)connection:(NSURLConnection *)__unused connection 
   didSendBodyData:(NSInteger)bytesWritten 
 totalBytesWritten:(NSInteger)totalBytesWritten 
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
    [super connection: connection didSendBodyData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
    self.totalBytesSent = totalBytesWritten;
    self.totalBytesExpectedToSend = totalBytesExpectedToSend;
}

你的上传进度块可能长这样:

……(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
    NSInteger queueTotalExpected = 0;
    NSInteger queueTotalSent     = 0;
    for (AFURLConnectionOperation *operation in self.operationQueue) {
        queueTotalExpected += operation.totalBytesExpectedToSend;
        queueTotalSent     += operation.totalBytesSent;
    }
    self.totalProgress = (double)queueTotalSent/(double)queueTotalExpected;
}];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接