需求分析
多张图片上传,依次上传,网络请求依赖关系。
创建队列
创建队列一个队列
// 创建一个队列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
// 设置最大线程数
queue.maxConcurrentOperationCount = 1;
创建任务
创建任务、并添加依赖关系一下下是我以多张图片上传为列()
//创建一个队列数组
NSMutableArray *operaQueueArray = [NSMutableArray array];
for (NSInteger i = 0; i < _dataSource.count; i++) {
UIImageJPEGRepresentation(_dataSource[i], 0.5);
NSBlockOperation *blockOpera = [NSBlockOperation blockOperationWithBlock:^{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); //默认创建的信号为0
//网络请求
[WSAction uploadImageUrl:WSApiUtl(circle_host, @"/wscircle/theme/upload-img") param:@{@"theme_id":theme_id, @"cid":_cid} data:UIImageJPEGRepresentation(_dataSource[i], 0.5) name:@"img" mimeType:nil success:^(BOOL isSuccessed) {
if (!isSuccessed) {
[WSHUD showHUDInfo:[NSString stringWithFormat:@"第%zd张图片上传失败", i+1]];
}
dispatch_semaphore_signal(semaphore); //这里请求成功信号量 +1 为1
} failed:^(NSError *error) {
dispatch_semaphore_signal(semaphore); //这里请求失败信号量 +1 为1
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); //走到这里如果信号量为0 则不再执行下面的代码 一直等待 信号量不是0 出现 才会执行下面代码,然后信号量为 - 1
}];
//将创建的任务添加到数组中
[operaQueueArray addObject:blockOpera];
}
//添加依赖关系
for (int i = 0; i < operaQueueArray.count; i++) {
if (i > 0) {
[operaQueueArray[i] addDependency:operaQueueArray[i - 1]];
}
}
添加任务到队列中
添加任务到队列中,并添加观察者
[queue addOperations:operaQueueArray waitUntilFinished:NO];
[queue addObserver:self forKeyPath:@"operationCount" options:0 context:nil];
实现网络监听方法
//监听网络请求
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"operationCount"]) {
NSOperationQueue *queue = (NSOperationQueue *)object;
if (queue.operationCount == 0) {
//主线程刷新界面
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.navigationController popViewControllerAnimated:YES];
});
}
}
}