开发中经常碰到一个页面需要依赖几个接口都请求成功后再刷新UI,可以如下
//先创建一个group
dispatch_group_t group = dispatch_group_create();
// 创建队列 serialQueue
dispatch_queue_t serialQueue =dispatch_queue_create("market", DISPATCH_QUEUE_SERIAL);
//网络请求一
dispatch_group_enter(group);
dispatch_group_async(group, serialQueue, ^{
NSLog(@"网络请求一执行完毕");
dispatch_group_leave(group);
});
// 网络请求二
dispatch_group_enter(group);
dispatch_group_async(group, serialQueue, ^{
NSLog(@"网络请求二执行完毕");
dispatch_group_leave(group);
});
//请求全部结束后,更新UI
dispatch_group_notify(group, serialQueue, ^{
dispatch_async(dispatch_get_global_queue(0,0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"UI更新完毕");
});
});
});
//主线程不受影响
NSLog(@"不卡主线程");