1.网络请求串行执行,执行完一个执行下一个,执行完最后一个进行操作
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t searialQueue = dispatch_queue_create("com.hmc.www", DISPATCH_QUEUE_SERIAL);
dispatch_group_enter(group);
dispatch_group_async(group, searialQueue, ^{
// 网络请求一
[WebRequest getDataSuccess:^(NSDictionary *dict) {
dispatch_group_leave(group);
} failure:^(NSError *err) {
dispatch_group_leave(group);
}];
});
dispatch_group_enter(group);
dispatch_group_async(group, searialQueue, ^{
// 网络请求二
[WebRequest getDataSuccess:^(NSDictionary *dict) {
dispatch_group_leave(group);
} failure:^(NSError *err) {
dispatch_group_leave(group);
}];
});
dispatch_group_enter(group);
dispatch_group_async(group, searialQueue, ^{
// 网络请求三
[WebRequest getDataSuccess:^(NSDictionary *dict) {
dispatch_group_leave(group);
} failure:^(NSError *err) {
dispatch_group_leave(group);
}];
});
//三个网络请求结束后,会进入这个方法,在这个方法中进行洁面的刷行
dispatch_group_notify(group, searialQueue, ^{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
// 刷新UI
});
});
});
2.网络请求并行执行,等待最后一个执行完成,用户进行操作
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
/创建全局并行/
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, ^{
NSLog(@"处理事件A");
for(inti =0; i<10000; i++) {
NSLog(@"打印i %d",i);
}
dispatch_semaphore_signal(semaphore);
});
dispatch_group_async(group, queue, ^{
NSLog(@"处理事件B");
for(inti =0; i<10000; i++) {
NSLog(@"打印j %d",i);
}
dispatch_semaphore_signal(semaphore);
});
dispatch_group_async(group, queue, ^{
NSLog(@"处理事件C");
for(inti =0; i<10000; i++) {
NSLog(@"打印k %d",i);
}
dispatch_semaphore_signal(semaphore);
});
dispatch_group_async(group, queue, ^{
NSLog(@"处理事件D");
for(inti =0; i<10000; i++) {
NSLog(@"打印l %d",i);
}
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_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
NSLog(@"处理事件E");
});