2011-11-08 36 views
7

我正在處理一個問題,我必須在隊列中下載大約10個不同的大文件,並且需要顯示指示總傳輸狀態的進度條。我在iOS4中使用ASIHTTPRequest可以很好地工作,但我試圖轉換到AFNetworking,因爲ASIHTTPRequest在iOS5中有問題,不再維護。從ASIHTTPRequest切換到AFNetworking - ASINetworkQueue問題

我知道你可以使用AFHTTPRequestOperation的downloadProgressBlock報告單個請求的進度,但我似乎無法找到一種方法來報告將在同一個NSOperationQueue上執行的多個請求的整體進度。

有什麼建議嗎?謝謝!

回答

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]; 
} 
+0

這是不好的MVC編碼實踐設計模式。 –

+0

也許吧。對於動態大小的內容而言,它是正確的工具。它將準確地顯示進度,而不必首先知道內容的大小。查找大文件(例如視頻或照片)的大小可能是一項昂貴的操作。 – clreina

0

你也可以繼承AFURLConnectionOperation有2個新的屬性:(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; 
}]; 
1
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) { 
    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite); 
}]; 

操作是AFHTTPRequestOperation