dispatch_group多个并发的请求总结果的管理

需求:公司当前的项目有一个页面是需要两个请求并发,且都成功后才算整个界面的数据请求成功

思路:首先想到的就是用dispatch_group,可写好后dispatch_notify并未等请求的block都执行完后才走,后就定义了个bool属性,采用kvo的方式实现了,事后还是感觉不是很好,就又找了些资料,经实践dispatch_group的enter group和leave group可实现需求

关键代码如下

dispatch_group_t group = dispatch_group_create();

dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

dispatch_group_enter(group);

dispatch_group_async(group, queue, ^{

//request

       [self requestPropertiesWithParams:skuParams success:^() {

            dispatch_group_leave(group);

       } failed:^(NSString *errMsg) {

          self.isFailed = YES;

         dispatch_group_leave(group);

     }];

});

dispatch_group_enter(group);

dispatch_group_async(group, queue, ^{

        [self requetGoodsPropertiesDetailWithParams:skugoodsParams                         success:^() {

              dispatch_group_leave(group);

       } failed:^(NSString *errMsg) {

            self.isFailed = YES;

             dispatch_group_leave(group);

      }];

});

dispatch_group_notify(group, dispatch_get_main_queue(), ^{

          if (self.isFailed == YES) {

                  if (self.requestFailedBlock) {

                     self.requestFailedBlock(@"请求失败");

                }

           }else{

                  [self filterData];

                 HLGoodsDetailModel *model =  [self          getNewModel:self.goodsDetailModel];

               [self.itemsDict setObject:model forKey:fileName];

               if (self.requestSuccessBlock) {

                    self.requestSuccessBlock(model);

               }

       }

});

你可能感兴趣的:(dispatch_group多个并发的请求总结果的管理)