1 有时候一个页面有好几个网络请求,而网络请求是异步的,有可能一个请求成功,另一个还在请求,在这个过程中如果刷新UI,可能会造成不好的用户体验以及在导致某些按钮点击无效,下面提供一种方法
创建并发队列,等所有请求结束,刷新UI
_queue = dispatch_queue_create("homeRequest", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
并发队列的特点是
以先进先出的方式,并发调度队列中的任务执行
如果当前调度的任务是同步执行的,会等待任务执行完成后,再调度后续的任务
如果当前调度的任务是异步执行的,同时底层线程池有可用的线程资源,会再新的线程调度后续任务的执行
@interface HomeViewController : BaseViewController
{
dispatch_queue_t _queue;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self requestUserData:YES pulling:NO];
}
- (void)requestUserData:(BOOL)refresh pulling:(BOOL)pulling {
if (_queue) {
return;
}
BOOL showLoading = NO; // 显示加载框
if (!pulling) {
if (!数据源1) {
showLoading = YES;
}
else if (!数据源2) {
showLoading = YES;
}
else if (!数据源3) {
showLoading = YES;
}
}
if (showLoading) {
[self showHUDTo:self.view animated:YES];
}
__weak typeof(self) weakSelf = self;
_queue = dispatch_queue_create("homeRequest", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
if ([JFUserInfoModel isLogin]) {
dispatch_group_async(group, _queue, ^{
[weakSelf 网络请求1];
});
dispatch_group_async(group, _queue, ^{
[weakSelf 网络请求2];
});
}
if (refresh || !_homeAdArray) {
dispatch_group_async(group, _queue, ^{
[weakSelf 网络请求3];
});
}
if (refresh || !_homeFeatureBannerArray) {
dispatch_group_async(group, _queue, ^{
[weakSelf 网络请求4];
});
}
if (refresh || !_homeProductBannerArray) {
dispatch_group_async(group, _queue, ^{
[weakSelf 网络请求5];
});
}
if (refresh || !_homeItemArray) {
dispatch_group_async(group, _queue, ^{
[weakSelf 网络请求6];
});
}
if (refresh) {
// 下拉刷新时
// do something
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
[weakSelf reload:showLoading pulling:pulling];
});
}
- (void)reload:(BOOL)showLoading pulling:(BOOL)pulling {
_queue = nil;
if (pulling) {
[_tableView.mj_header endRefreshing];
}
else if (showLoading){
[self hideHUDView:self.view animated:YES]; // 隐藏loading框
}
[self setupVenderView];
[_tableView reloadData];
}
// 网络请求1
- (void) request网络请求1 {
__block dispatch_semaphore_t sem = dispatch_semaphore_create(0);
Request *request = [[Request alloc] init];
[self post:request forResponseClass:[Response class] onSuccess:^(Response *response) {
if ([response success]) {
_integral = ((Response *)response).data;
}
dispatch_semaphore_signal(sem);
} onFailure:^(NSError *error) {
dispatch_semaphore_signal(sem);
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
}
// 网络请求2
- (void) request网络请求2 {
__block dispatch_semaphore_t sem = dispatch_semaphore_create(0);
[self post:request forResponseClass:[indingResponse class] onSuccess:^(Response *response) {
if ([response success]) {
[self setupVenderDataWithData:response];
}
dispatch_semaphore_signal(sem);
} onFailure:^(NSError *error) {
dispatch_semaphore_signal(sem);
}];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
}
网友评论