/**
* 使用dispatch_group,异步多请求
*/
- (void)asyncBaseData
{
// 全局并行队列
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
// 创建一个group
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, globalQueue, ^{
// 执行请求1... (这里的代码需要时同步执行才能达到效果)
});
dispatch_group_async(group, globalQueue, ^{
// 执行请求2...
});
dispatch_group_async(group, globalQueue, ^{
// 执行请求N...
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"全部请求执行完毕!");
});
}
当dispatch_group_async的block里面执行的是异步任务,如果还是使用上面的方法你会发现异步任务还没跑完就已经进入到了dispatch_group_notify方法里面了,这时用到dispatch_group_enter和dispatch_group_leave就可以解决这个问题:
#pragma mark - 下载基础数据
- (void)downloadBaseData
{
// 全局变量group
group = dispatch_group_create();
// 并行队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 进入组(进入组和离开组必须成对出现, 否则会造成死锁)
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
// 执行异步任务1
[self fetchBaseData];
});
// 进入组
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
// 执行异步任务2
[self fetchInspectorBaseData];
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
ILog(@"全部基础数据下载完毕!");
[[AppDelegate sharedDelegate] showMainView];
});
}
#pragma mark - 获取基础数据
- (void)fetchBaseData
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[SVProgressHUD showWithStatus:@"下载基础数据中..."];
});
NSDictionary *params = @{ kPage: @0, kPageSize: @9999 };
[BaseDataService fetchBaseDataWithParams:params showHUD:NO success:^(NSDictionary *response) {
if ([response[kStatusCode] intValue] == kSuccessCode) {
NSArray *array = [BaseDataModel arrayOfModelsFromDictionaries:response[@"rows"] error:nil];
if (!array || !array.count ) {
[SVProgressHUD showErrorWithStatus:@"下载基础数据失败"];
return;
}
// 保存数据库
[BaseDataService saveBaseData:array];
// 离开组
dispatch_group_leave(group);
}
} failure:^(NSError *error) {
}];
}
#pragma mark - 获取巡查基础数据
- (void)fetchInspectorBaseData
{
NSDictionary *params = @{ kPage: @0, kPageSize: @9999 };
[BaseDataService fetchInspectorBaseDataWithParams:params showHUD:NO success:^(NSDictionary *response) {
[SVProgressHUD dismiss];
if ([response[kStatusCode] intValue] == kSuccessCode) {
NSArray *array = [InspectorBaseDataModel arrayOfModelsFromDictionaries:response[@"rows"] error:nil];
if (!array || !array.count ) {
[SVProgressHUD showErrorWithStatus:@"下载巡查基础数据失败"];
return;
}
// 保存数据库
[BaseDataService saveInspectorBaseData:array];
// 离开组
dispatch_group_leave(group);
}
} failure:^(NSError *error) {
}];
}
group是一个全局变量:
@interface LoginViewController ()
{
dispatch_group_t group;
}
当执行异步任务1的时候进入组,在异步任务1执行完毕后离开组,执行异步任务2前进入组,异步任务2执行完成后离开组,只有当这两个异步任务都执行完毕了才会执行dispatch_grout_notify方法。