2011-12-07 33 views
5

Tôi đang sử dụng mã này để lặp qua một mảng để tải xuống nhiều tệp và ghi vào đĩa.AFnetworking tải xuống nhiều tệp

-(void)download 
{ 
//set url paths 
for (NSString *filename in syncArray) 
{ 
    NSString *urlpath = [NSString stringWithFormat:@"http://foo.bar/photos/%@", filename]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlpath]]; 
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:filename]; 
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO]; 

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"Successfully downloaded file to %@", path); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Error: %@", error); 
}]; 


[operation start]; 

nhưng vấn đề là nó gọi là khối thành công sau mỗi tập tin được thực hiện, (mà nó nên) nhưng tôi chỉ cần một cuộc gọi cuối cùng lại để tải lại một số dữ liệu và kết thúc một tiến bộ HUD.

Bất kỳ con trỏ nào đi đúng hướng đều tuyệt vời.

+0

Hey, Bạn gọi hàm này ở đâu? Trong AppDelegate hoặc trong một bộ điều khiển cụ thể? Ngoài ra, điều gì sẽ xảy ra nếu ứng dụng bị thoát trước khi quá trình tải xuống hoàn tất? Cảm ơn – manishKungwani

Trả lời

5

Có lẽ một ngày nào đó điều này sẽ giúp ai đó, nhưng tôi đã có thể sử dụng giải pháp có thể có vấn đề lớn nhưng không sao cho việc sử dụng đơn giản của tôi.

Tôi vừa xóa từng dòng khỏi mảng đồng bộ hóa sau khi được xử lý rồi chạy mã tôi cần.

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"Successfully downloaded file to %@", path); 
    [SVProgressHUD showWithStatus:@"Updating Photos"]; 
    [syncArray removeObject:filename]; 
    if (!syncArray || !syncArray.count) 
    { 
    NSLog(@"array empty"); 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self]; 
     [SVProgressHUD dismissWithSuccess:@"Photos Updated"]; 
    } 
5

Bạn có thể sử dụng AFHTTPClient để enqueueBatchOperations và điều này có completionBlock được gọi là khi tất cả các hoạt động đã kết thúc. Nên chính xác những gì bạn đang tìm kiếm.

+0

Tôi đồng ý, đây là giải pháp tốt hơn. – ajmccall

+1

Trang liên kết hiện không có sẵn ...... –

Các vấn đề liên quan