Wait until multiple networking requests have all executed - including their completion blocks
Use dispatch groups.
dispatch_group_t group = dispatch_group_create();MyCoreDataObject *coreDataObject;dispatch_group_enter(group);AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];[operation1 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { coreDataObject.attribute1 = responseObject; sleep(5); dispatch_group_leave(group);}];[operation1 start];dispatch_group_enter(group);AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { coreDataObject.attribute2 = responseObject; sleep(10); dispatch_group_leave(group);}];[operation2 start];dispatch_group_wait(group, DISPATCH_TIME_FOREVER);dispatch_release(group);[context save:nil];
AFNetworking has designed method for this kind of operations, which abstracts from GCD:
-enqueueBatchOfHTTPRequestOperationsWithRequests:progressBlock:completionBlock:
-enqueueBatchOfHTTPRequestOperations:progressBlock:completionBlock:
Take a look at FAQ
I belive something like this:
NSMutableArray *mutableOperations = [NSMutableArray array];for (NSURL *fileURL in filesToUpload) { NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil]; }]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [mutableOperations addObject:operation];}NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) { NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);} completionBlock:^(NSArray *operations) { NSLog(@"All operations in batch complete");}];[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
refering to docs: http://cocoadocs.org/docsets/AFNetworking/2.5.0/