The below uses dispatch groups to hold off starting another block till the groups work has been completed.
First change your data methods to not be wrapped in dispatch_async
and accept a completion block, calling that at the end of the NSURLSessionDataTask
s completionHandler
:
-(void)getListaServiciosPorLocal:(id)whatEver withCompletionBlock:(dispatch_block_t)block
{
NSURL *url = [NSURL URLWithString:urlConnection];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.timeoutIntervalForRequest = 30;
sessionConfiguration.timeoutIntervalForResource = 60;
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
__block NSError *jsonError;
NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *) response;
if(!error) {
if(urlResponse.statusCode == 200) {
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&jsonError];
if(response) {
NSString *resp = [NSString stringWithFormat:@"%@", [dataResponse objectForKey:@"resp"]];
if([resp isEqualToString:@"1"]) {
_json = [dataResponse objectForKey:@"data"];
[_arrServiciosTmp addObjectsFromArray:(NSArray *)_json];
} else {
NSString *message = [dataResponse objectForKey:@"description"];
}
} else {
self.lblMensaje.text = @"Ha ocurrido un error al obtener la información, por favor, vuelva a intentarlo en unos momentos.";
}
} else {
completion(nil);
}
} else {
NSLog(@"Error en Task");
}
block(); // Notify completion block
});
}
Now when you call these methods:
dispatch_group_t group = dispatch_group_create();
dispatch_async(queue, ^(void) {
NSLog(@"llego a buscar servicios por local");
for (NSDictionary *local in _arrLocalesTmp) {
dispatch_group_enter(group);
[self getListaServiciosPorLocal:[local objectForKey:@"idLocal"] withCompletionBlock:^{
dispatch_group_leave(group);
}];
}
NSLog(@"llego a buscar profesionales por local");
for (NSDictionary *local in _arrLocalesTmp) {
dispatch_group_enter(group);
[self getListaProfesionalesPorLocal:[local objectForKey:@"idLocal"] withCompletionBlock:^{
dispatch_group_leave(group);
}];
}
});
dispatch_group_notify(group, dispatch_get_main_queue(),^{
[self setFormularioConsultaCompleto];
});
(Adapted from this answer)