在循环内部运行中运行请求操作

我怎样才能在1请求的成功块内运行多个请求,并等待它完成?

[manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"%@ Response: \n%@", url, responseObject); resultsArray = [[NSMutableArray alloc] init]; for (NSDictionary *json in [responseObject objectForKey:@"items"]) { [self getDetails:json]; } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { [SVProgressHUD dismiss]; }]; 

在getDetails中:(id)json是加载参数基于主要请求结果的请求组的方法。

例如:我想从API中请求学生列表,然后在成功块上。 对于每个学生,我想从另一个表(另一个请求)获取相关数据,并把它们放在我的NSObject上。

编辑这里是我的getDetails方法

 - (AFHTTPRequestOperation *)getDetails:(NSDictionary *)json { NSLog(@"Start Op %@",[json objectForKey:@"related_salon"]); NSString *url = [NSString stringWithFormat:@"%@read/salons/%@",SERVER_API_URL,[json objectForKey:@"related_salon"]]; NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:req]; //op.responseSerializer = [AFJSONResponseSerializer serializer]; [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"Success %@",[json objectForKey:@"name"]); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Failed Op %@",error.localizedDescription); }]; //AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:req]; //op.responseSerializer = [AFJSONResponseSerializer serializer]; [op start]; return op; } 

AFNetworking GET方法返回一个ATHTTPRequestOperation (一个NSOperation子类)。 你可以让你的getDetails方法返回该对象。 然后,您可以创build一个新的操作,取决于您在最后运行的操作:

 NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{ // add here whatever you want to perform when all the getDetails calls are done, // eg maybe you want to dismiss your HUD when all the requests are done. [SVProgressHUD dismiss]; }]; [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"%@ Response: \n%@", url, responseObject); resultsArray = [[NSMutableArray alloc] init]; for (NSDictionary *json in [responseObject objectForKey:@"items"]) { NSOperation *operation = [self getDetails:json]; [completionOperation addDependency:operation]; } [[NSOperationQueue mainQueue] addOperation:completionOperation]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { [SVProgressHUD dismiss]; }]; 

同样,这是假设getDetails正在做自己的GET调用,并且你改变getDetails (a)捕获由GET返回的NSOperation和(b)返回它。