利用线程组请求多个网络, 等多个网络请求成功再回到主线程刷新UI

利用线程组请求多个网络, 等多个网络请求成功再回到主线程刷新UI

关键函数

dispatch_group_create() // 创建线程组
dispatch_group_enter  // 进入线程组
dispatch_group_leave // 离开线程组
dispatch_group_notify // 异步任务全部执行完毕

PS: dispatch_group_enterdispatch_group_leave必须成对出现, 否则会崩溃

Example

- (void)testGroup {
    dispatch_group_t group = dispatch_group_create();
       
    dispatch_group_enter(group);
    [self request1Success:^{
        dispatch_group_leave(group);
    }];
    dispatch_group_enter(group);
    [self request2Success:^{
        dispatch_group_leave(group);
    }];
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"全部请求完成, 刷新UI");
    });
}

// 第1个网络
- (void)request1Success:(void(^)(void))success {
    NYLReq *req = [[NYLReq alloc] initWithConsultID:self.consultID];
    [req gddStartWithCompletionBlockWithSuccess:^(id returnData) {
        if(success) {
        	success();
        }
    }];
}

// 第2个网络
- (void)request2Success:(void(^)(void))success {
    NYLReq *req = [[NYLReq alloc] initWithConsultID:self.consultID];
    [req gddStartWithCompletionBlockWithSuccess:^(id returnData) {
	   if(success) {
        	success();
        }
    }];
}

你可能感兴趣的:(iOS)