1、多个网络请求完成后通知继续执行
创建一个队列组, 每次网络请求前先dispatch_group_enter,请求回调后再dispatch_group_leave,对于enter和leave必须配合使用,有几次enter就要有几次leave,否则group会一直存在。当所有enter的block都leave后,会执行dispatch_group_notify的block
@property (nonatomic, strong) dispatch_group_t group;
@property (nonatomic, strong) dispatch_queue_t queue;
//1.创建队列组
_group = dispatch_group_create();
//2.创建队列
_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//3.网络请求
[self load1];
[self load2];
[self load3];
//4.都完成后会自动通知
dispatch_group_notify(_group, dispatch_get_main_queue(), ^{
NSLog(@"请求完成");
});
//5.网络请求1
请求前:dispatch_group_enter(_group);
请求回调:dispatch_group_async(_group, _queue, ^{
NSLog(@"请求成功了1");
});
dispatch_group_leave(_group);
//6.网络请求2
请求前:dispatch_group_enter(_group);
请求回调:dispatch_group_async(_group, _queue, ^{
NSLog(@"请求成功了2");
});
dispatch_group_leave(_group);
//7.网络请求3
请求前:dispatch_group_enter(_group);
请求回调:dispatch_group_async(_group, _queue, ^{
NSLog(@"请求成功了3");
});
dispatch_group_leave(_group);
2、多个异步请求,顺序回调结果
@property (nonatomic, strong) NSConditionLock *lock;
@property (nonatomic, strong) dispatch_queue_t queue;
//创建锁和队列
_lock = [[NSConditionLock alloc] initWithCondition:0];//默认解锁条件为0
_queue = dispatch_queue_create("concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
//添加假数据
NSArray *imageUrlArray = @[@"http://pic.qiantucdn.com/58pic/22/72/00/57c6575a13516_1024.jpg",@"http://d.hiphotos.baidu.com/image/pic/item/34fae6cd7b899e51c46401174ea7d933c9950dce.jpg",@"http://img.zcool.cn/community/0117e2571b8b246ac72538120dd8a4.jpg@1280w_1l_2o_100sh.jpg",@"http://img.zcool.cn/community/0125fd5770dfa50000018c1b486f15.jpg@1280w_1l_2o_100sh.jpg",@"http://pic14.nipic.com/20110605/1369025_165540642000_2.jpg"];
//循环请求
for (int i = 0; i < imageUrlArray.count; i++) {
NSURL *imgeUrl = [NSURL URLWithString:imageUrlArray[i]];
SDWebImageDownloaderOptions options = 0;
//SDWebImageDownloader下载
SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
[downloader downloadImageWithURL:imgeUrl options:options progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) { } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
dispatch_async(_queue, ^{
[_lock lockWhenCondition:i];//首次解锁为0
NSLog(@"%d",i);
[_lock unlockWithCondition:i+1];//加锁,解锁条件+1
});
}];
}