iOS多图上传涉及到多线程问题,个人比较喜欢使用GCD操作,下边是最近写的一个多图上传代码,附带相关注释
__block BOOL allSucc = YES; __block int m = 0; //创建线程队列上传图片 self.photoDictArray = [NSMutableArray array]; dispatch_queue_t uploadQueue = dispatch_queue_create("upload", DISPATCH_QUEUE_CONCURRENT); dispatch_group_t group = dispatch_group_create(); dispatch_semaphore_t signal = dispatch_semaphore_create(3);//线程并发数3(保持3张图片同时上传) for (UIImage * image in self.dataImageArr) { dispatch_group_enter(group); dispatch_async(uploadQueue, ^{ dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER); m++; if (allSucc == NO) { dispatch_semaphore_signal(signal); dispatch_group_leave(group); NSLog(@"本次上传被取消"); }else{ [FileUploader uploadImageToQiniu:image finishAction:^(NSString *url, NSError *error) { if (!error) { //上传成功 [self.photoDictArray addObject:@{@"url":url, @"height":@(image.size.height), @"width":@(image.size.width)}]; dispatch_semaphore_signal(signal); dispatch_group_leave(group); NSLog(@"第%d次上传成功",m); }else{ //上传失败 allSucc = NO; dispatch_semaphore_signal(signal); dispatch_group_leave(group); NSLog(@"第%d次上传失败",m); } }]; } }); } dispatch_group_notify(group, dispatch_get_main_queue(), ^{ if (!allSucc) { //个别图片上传失败 [TipsView showTips:@"图片上传失败,请重试"]; return; } // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.photoDictArray options:NSJSONWritingPrettyPrinted error:nil]; // NSString * imagesStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; //全部上传成功 [HttpClient postUrl:URL_Gossip_Publish dic:@{@"content":self.textView.text, @"images":self.photoDictArray} finish:^(NSURLSessionDataTask *task, id responseObj, NSError *error) { if (self.submitAction) { self.submitAction(error); } if (!error) { if (self.isHTMLPush) { [TipsView showTips:@"发布成功!"]; [self.navigationController popViewControllerAnimated:YES]; }else{ NativeViewController * controller = [[NativeViewController alloc]init]; controller.url = responseObj[@"data"][@"appUrl"]; [[AppDelegate rootNavController] pushViewController:controller animated:YES]; NSMutableArray * controllerArr = [[NSMutableArray alloc]initWithArray:[AppDelegate rootNavController].viewControllers]; if ([controllerArr containsObject:self]) { [controllerArr removeObject:self]; } [AppDelegate rootNavController].viewControllers = [[NSArray alloc]initWithArray:controllerArr]; } } }]; });
采用信号量和group来控制线程并发,所有图片上传完毕,通过dispatch_group_notify获取到上传结束的动作通知,然后进行下一步操作