dispatch_group控制多個非同步介面

weixin_34402408發表於2019-01-03

1.多個介面請求完成後重新整理UI

dispatch_group_t group_t = dispatch_group_create();
    dispatch_group_async(group_t, dispatch_get_main_queue(), ^{
        [weakSelf request1:group_t];
    });
 dispatch_group_async(group_t, dispatch_get_main_queue(), ^{
            [weakSelf request2:group_t];
        });
    
    dispatch_group_notify(group_t, dispatch_get_main_queue(), ^{
       [weakSelf.tableView reloadData];
    });

2.dispatch_group_enter(group)、dispatch_group_leave(group)一一對應

- (void)request1:(dispatch_group_t)group_t {
    WS(weakSelf)    
dispatch_group_enter(group_t);
[manager GET:APIManager.share.baseUrl parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        progress(downloadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
weakSelf.data1 = responseObject;
  dispatch_group_leave(group_t);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
      dispatch_group_leave(group_t);
    }];
}

- (void)request2:(dispatch_group_t)group_t {
    WS(weakSelf)    
dispatch_group_enter(group_t);
[manager GET:APIManager.share.baseUrl parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        progress(downloadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
weakSelf.data2 = responseObject;
  dispatch_group_leave(group_t);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
      dispatch_group_leave(group_t);
    }];
}

相關文章