如何在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;
}
答案 0 :(得分:0)
AFNetworking GET
方法返回ATHTTPRequestOperation
(NSOperation
子类)。您可以让getDetails
方法返回该对象。然后,您可以创建一个新操作,该操作取决于您最后运行的那些操作:
NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
// add here whatever you want to perform when all the getDetails calls are done,
// e.g. 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)捕获NSOperation
返回的GET
和}(b)返回它。