ios 信号量处理网络请求并发
2017-11-29 本文已影响0人
Mr_Lxh
用信号量 处理多个网络请求
#-(void)loadData2{
[self showHUD:@"加载中"];
Server *ser=[[Server alloc]init];
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 创建信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[ser QueryBindCardWithCrashFlag:@"" Success:^(id obj) {
// [self.myTableView headerEndRefreshing];
ServerResponse *response = (ServerResponse *)obj;
if(response.state == 0)
{
cardModel = response.data;
if ([cardModel.isOpenMember intValue] ==1)
{//已开通
// 如果请求成功,发送信号量
dispatch_semaphore_signal(semaphore);
}else{
[self showHudTipStr:@"暂未开通运友宝"];
dispatch_semaphore_signal(semaphore);
}
}
else
{
dispatch_semaphore_signal(semaphore);
}
} failture:^{
[self hideHUD];
dispatch_semaphore_signal(semaphore);
}];
// 在网络请求任务成功之前,信号量等待中
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 创建信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[ser QueryMoneyWithcustAcctId:cardModel.custAcctId Reserve:@"" Success:^(id obj) {
ServerResponse *response = (ServerResponse *)obj;
[self hideHUD];
NSLog(@"%d",response.state);
if (response.state == 0)
{
//查询余额
moneyModel = response.data;
if (moneyModel.totalBalance==nil) {
moneyModel.totalBalance=@"0";
}
if (moneyModel.totalTranOutAmount==nil) {
moneyModel.totalTranOutAmount=@"0";
}
dispatch_semaphore_signal(semaphore);
}
else
{
[self showHudTipStr:response.message];
dispatch_semaphore_signal(semaphore);
}
} failture:^{
[self showHudTipStr:@"连接服务器失败"];
}];
// 在网络请求任务成功之前,信号量等待中
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
});
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
[self hideHUD];
[self.myTableView headerEndRefreshing];
[self.myTableView reloadData];
});
});
}