调度iOS的问题

时间:2014-04-24 01:14:32

标签: ios dispatch

我是iOS的新手,我无法理解和应用好的调度...我有一个应用程序,我需要在for循环中查询网站(api),我需要制作的那个循环的结束在另一个循环中进一步查询,最后,在两个循环结束时需要切换视图。

我现在有了这段代码(经过多次试验和错误但仍无效):

dispatch_queue_t queue = dispatch_queue_create("threadServicios", DISPATCH_QUEUE_SERIAL);

    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);

    dispatch_async(queue, ^(void) {
        NSLog(@"llego a buscar servicios por local");
        for (NSDictionary *local in _arrLocalesTmp) {
            [self getListaServiciosPorLocal:[local objectForKey:@"idLocal"]];
            //this function calls another function that consumes a web service and get a json
        }

        procced = YES;

        NSLog(@"llego a buscar profesionales por local");
        for (NSDictionary *local in _arrLocalesTmp) {
            [self getListaProfesionalesPorLocal:[local objectForKey:@"idLocal"]];
            //this function calls another function that consumes a web service and get a json
        }

        procced2 = YES;

        dispatch_group_leave(group);
    });

    dispatch_group_notify(group, dispatch_get_main_queue(),^{
        NSLog(@"dispatch procced 1");
        if (procced && procced2) {
            [self setFormularioConsultaCompleto];
        }
    });

函数[self getListaServiciosPorLocal:[Local objectForKey:@" idLocal"]];如下:

dispatch_async(dispatch_get_main_queue(), ^(void) {
    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");
        }                            
    });

函数[self getListaProfesionalesPorLocal:[Local objectForKey:@" idLocal"]];类似但获得其他信息

问题是app调用了这个函数[self setFormularioConsultaCompleto]; (更改视图)但上述功能仍然无法从webservice获取所有数据。

对不起,但我放弃了,希望可以帮助我!

谢谢!

1 个答案:

答案 0 :(得分:0)

以下使用派遣小组推迟开始另一个小组,直到小组工作完成。

首先将您的数据方法更改为不包含在dispatch_async中并接受完成块,并在NSURLSessionDataTask completionHandler {<1}}的末尾调用它:

-(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                        
    });
}

现在,当您调用这些方法时:

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];
});

(改编自this answer