关于iOS信号量控制网络请求先后顺序执行或终止
网络块的学习一直是iOS的学习开发难点,今天就这块中的难点闲谈一下。。
废话不多,先上代码:
//处理多个事件的并发行为
- (void)requestForThreeResponse{
__weak typeof(self) weakself = self;
[[UIApplication sharedApplication].keyWindow addSubview:self.hud];
[self.dataArr removeAllObjects];
[self.tipInfoModelsArr removeAllObjects];
// /创建信号量/
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
// /创建全局并行/
self.count=3;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
[weakselfgetAmountMoneySuccess:^(BOOLisSuccess) {
if(isSuccess) {
dispatch_semaphore_signal(semaphore);
}else{
weakself.count--;
dispatch_semaphore_signal(semaphore);
}
}];
});
dispatch_group_async(group, queue, ^{
[weakselfgetFinancialLectureListSuccess:^(BOOLisSuccess) {
if(isSuccess) {
dispatch_semaphore_signal(semaphore);
}else{
weakself.count--;
dispatch_semaphore_signal(semaphore);
}
}];
});
dispatch_group_async(group, queue, ^{
[weakselfrequestForQuestionSuccess:^(BOOLisSuccess) {
if(isSuccess) {
dispatch_semaphore_signal(semaphore);
}else{
weakself.count--;
dispatch_semaphore_signal(semaphore);
}
}];
});
dispatch_group_notify(group, queue, ^{
// /四个请求对应四次信号等待/
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_async(dispatch_get_main_queue(), ^{
if(weakself.count<=0) {
weakself.isHidden=NO;
_emptyDataHandler.errorDescription = @"网络加载出错了,请查看一下网络环境";
_emptyDataHandler.type = EmptyDataDisplayTypeError;
}else{
// _emptyDataHandler.type = EmptyDataDisplayTypeSuccess;
weakself.isHidden=YES;
}
[weakselfloadNewDataWithHideen:weakself.isHidden];
[weakself.scrollView reloadEmptyDataSet];
});
});
}
代码思路过程:
// /创建信号量/ -> /创建全局并行/ -> /多个请求对应多次信号等待/
这样就可以通过对网络请求封装的顺序及中止控制了