ios使用dispatch_group_t来处理多个异步调用

时间:2016-06-20 13:16:06

标签: ios json asynchronous

我尝试设置一个dispatch_group,这样我就可以进行多次异步调用,将多个返回的数据存储到一个数组中,然后在完成所有调用后处理它们。这是获取JSON的代码:

- (void) getJSONFromArrayOfURLS : (NSArray*) arrURLS {

//create dispatch group
dispatch_group_t jsonGroup = dispatch_group_create();

for(NSURL* thisURL in arrURLS) {

    //enter dispatch group
    dispatch_group_enter(jsonGroup);

    //make nsurlsession query here
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfig.timeoutIntervalForResource = 10;

    NSURLSession* session = [NSURLSession sharedSession];
    NSURLSessionDataTask* dataTask = [session dataTaskWithURL:thisURL completionHandler:^(NSData* data, NSURLResponse* response, NSError* error) {

        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*) response;

        if (httpResponse.statusCode == 200) {

            //hit the servers but they returned an error
            if (error) {

                NSString* strErrMsg;

                if (error.code == NSURLErrorCancelled) {
                    strErrMsg = @"The connection to the servers was lost. ";
                } else {
                    strErrMsg = [NSString stringWithFormat:@"The server sent this error message: \n%@", error.localizedDescription];
                }


                UIAlertController* alertController = [UIAlertController
                                                      alertControllerWithTitle:@"There was an error connecting to the servers."
                                                      message: strErrMsg
                                                      preferredStyle:UIAlertControllerStyleAlert];

                UIAlertAction* okAction = [UIAlertAction
                                           actionWithTitle:NSLocalizedString(@"OK", @"OK action")
                                           style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction *action) {



                                           }
                                           ];

                [alertController addAction:okAction];

                [self presentViewController:alertController animated:YES completion:nil];

            //hit servers successfully
            } else {

                //deseriealize the return
                id JSONObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

                [self.arrReturnedData addObject:JSONObject];

            }

        } else {

            //never hit the servers
            UIAlertController* alertController = [UIAlertController
                                                  alertControllerWithTitle:@"There was an error connecting to the servers."
                                                  message: [NSString stringWithFormat:@"The server replied with the following status:\n\n%i", (int)httpResponse.statusCode]
                                                  preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction* okAction = [UIAlertAction
                                       actionWithTitle:NSLocalizedString(@"OK", @"OK action")
                                       style:UIAlertActionStyleDefault
                                       handler:^(UIAlertAction *action) {

                                       }
                                       ];

            [alertController addAction:okAction];

            [self presentViewController:alertController animated:YES completion:nil];

        }

    }];

    [dataTask resume];

    dispatch_group_leave(jsonGroup);
}


dispatch_group_notify(jsonGroup, dispatch_get_main_queue(), ^(void)  {

    NSLog(@"%@", self.arrReturnedData);

});

}

我遇到的问题是,如果我在这一行断点,我可以看到JSON数据成功进入:

[self.arrReturnedData addObject:JSONObject];

数组中有一个对象(NSDictionary),带有我期待的数据。但是,更进一步,在这里:

dispatch_group_notify(jsonGroup, dispatch_get_main_queue(), ^(void)  {

    NSLog(@"%@", self.arrReturnedData);

});

数组为空。我是dispatch_groups的新手,但我的理解是,一旦输入到jsonGroup的所有任务都完成,就会调用group_notify。我没有在任何地方重置数组,所以我的想法是在异步过程中填充数组之前调用它。我接近这个错误吗?

0 个答案:

没有答案