先上方法名,該方法提供了幾個(gè)圖片縮放的預(yù)處理功能时迫,以及上傳失敗再次上傳的功能。由于我們后臺(tái)不支持修改圖片名字谓晌,就去除了圖片命名的功能掠拳。
用到的知識(shí)點(diǎn)主要是:
Http鏈接、多線程GCD
/**
上傳多張圖片
@param images 圖片數(shù)組
@param url URL
@param paramsDic 參數(shù)
@param imageScale 上傳圖片縮放比例
@param times 上傳失敗-重新上傳次數(shù)
@param uploadImageBlock 回調(diào)函數(shù)
*/
+(void)uploadImages:(NSArray<UIImage *> *)images url:(id)url params:(id)paramsDic imageScale:(CGFloat)imageScale reConnectTimes:(NSInteger)times finishBlock:(void (^)(NSArray<NSString*> *errorStrArr, NSArray<ResModel*> *modelArr))uploadImageBlock;
下面講講主要實(shí)現(xiàn)思路:
1.先對(duì)上傳的URL路徑進(jìn)行合法性的判斷纸肉;
2.用于回調(diào)的block賦值溺欧;
3.組裝上傳接口的傳參,防止漏傳參數(shù)柏肪;
4.生成NSURLRequest的對(duì)象姐刁,設(shè)置HTTPMethod、HTTPBody烦味、TimeoutInterval聂使、host等屬性;
5.建立dispatch_group對(duì)象,用于管理請(qǐng)求(由于NSURLSessionDataTask創(chuàng)建時(shí)默認(rèn)為異步的柏靶,為了加快上傳的速度弃理,通過(guò)dispatch_group管理這些請(qǐng)求),詳見(jiàn)下面代碼:
//圖片請(qǐng)求結(jié)果
__block NSMutableArray* resModelResultArr = [[NSMutableArray alloc]init];
__block NSMutableArray* errorResultArr = [[NSMutableArray alloc]init];
//通過(guò)dispatch_group 管理多個(gè)請(qǐng)求
dispatch_queue_t dispatchQueue = dispatch_queue_create("uploadImageQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t dispatchGroup = dispatch_group_create();
for (int i = 0; i < images.count; i++) {
ResModel* model=[[ResModel alloc]init];
model.serviceStr=paramsDic[@"service"];
model.requestUrlStr=urlReq.URL.absoluteString;
model.requestStr=ccstr(@"%@%@",urlReq.URL.absoluteString,paraString);
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
dispatch_group_enter(dispatchGroup);
NSURLRequest* request = [CC_UploadImagesTool recaculateImageDatas:images[i] imageScale:imageScale paramsDic:paramsDic request:urlReq];
[CC_UploadImagesTool requestSingleImageWithSession:session executorDelegate:executorDelegate request:request index:i+1 reConnectTimes:times model:model finishBlock:^(NSString *error, ResModel *resModel) {
if (error) {
[errorResultArr addObject:error];
}
[resModelResultArr addObject:resModel];
dispatch_group_leave(dispatchGroup);
}];
});
}
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"所有圖片上傳完成-----end");
[session finishTasksAndInvalidate];
executorDelegate.finishUploadImagesCallbackBlock(errorResultArr, resModelResultArr);
});
這邊將每個(gè)請(qǐng)求封裝為單獨(dú)的一個(gè)方法宿礁,方便請(qǐng)求失敗時(shí)重新發(fā)起請(qǐng)求
+(void)requestSingleImageWithSession:(NSURLSession*)session executorDelegate:(CC_HttpTask *)executorDelegate request:(NSURLRequest*)request index:(int)index reConnectTimes:(NSInteger)reConnectTimes model:(ResModel*)model finishBlock:(void (^)(NSString *, ResModel *))block{
executorDelegate.finishCallbackBlock = block; // 綁定執(zhí)行完成時(shí)的block
__block NSInteger reTryTimes = reConnectTimes;
__weak __typeof(self)weakSelf = self;
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
__strong __typeof(self)strongSelf = weakSelf;
if (error) {
//重新發(fā)起請(qǐng)求
if (reTryTimes == 0) {
[model parsingError:error];
executorDelegate.finishCallbackBlock(model.errorMsgStr, model);
}else{
NSLog(@"上傳第%d張圖片失敗-----重連還剩%ld次", index, reTryTimes);
reTryTimes--;
[strongSelf requestSingleImageWithSession:session executorDelegate:executorDelegate request:request index:index reConnectTimes:reTryTimes model:model finishBlock:block];
}
}else{
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
model.resultDic = result;
NSLog(@"上傳第%d張圖片成功-----result:%@", index, result);
executorDelegate.finishCallbackBlock(model.errorMsgStr, model);
}
}];
[task resume];
}
下面對(duì)每個(gè)請(qǐng)求進(jìn)行封裝案铺,通過(guò)數(shù)據(jù)流的方式上傳數(shù)據(jù)蔬芥,從而避免了不知道設(shè)什么mimeType
+(NSURLRequest*)recaculateImageDatas:(UIImage*)image imageScale:(CGFloat)imageScale paramsDic:(NSDictionary*)paramsDic request:(NSMutableURLRequest*)urlReq{
NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//分界線 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//結(jié)束符 AaB03x--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
//http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
//參數(shù)的集合的所有key的集合
NSArray *keys= [paramsDic allKeys];
//遍歷keys
for(int i=0;i<[keys count];i++) {
//得到當(dāng)前key
NSString *key=[keys objectAtIndex:i];
//添加分界線梆靖,換行
[body appendFormat:@"%@\r\n",MPboundary];
//添加字段名稱,換2行
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key];
//添加字段的值
[body appendFormat:@"%@\r\n",[paramsDic objectForKey:key]];
}
//聲明myRequestData笔诵,用來(lái)放入http body
NSMutableData *myRequestData=[NSMutableData data];
//將body字符串轉(zhuǎn)化為UTF8格式的二進(jìn)制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
//要上傳的圖片--得到圖片的data
NSData* data = UIImageJPEGRepresentation(image, imageScale);
NSMutableString *imgbody = [[NSMutableString alloc] init];
//添加分界線返吻,換行
[imgbody appendFormat:@"%@\r\n",MPboundary];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat =@"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
[imgbody appendFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@\"\r\n", fileName];
//聲明上傳文件的格式
[imgbody appendFormat:@"Content-Type: application/octet-stream; charset=utf-8\r\n\r\n"];
//將body字符串轉(zhuǎn)化為UTF8格式的二進(jìn)制
[myRequestData appendData:[imgbody dataUsingEncoding:NSUTF8StringEncoding]];
//將image的data加入
[myRequestData appendData:data];
[myRequestData appendData:[ @"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//聲明結(jié)束符:--AaB03x--
NSString *end=[[NSString alloc]initWithFormat:@"%@\r\n",endMPboundary];
//加入結(jié)束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//設(shè)置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
//設(shè)置HTTPHeader
[urlReq setValue:content forHTTPHeaderField:@"Content-Type"];
//設(shè)置Content-Length
[urlReq setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//設(shè)置http body
[urlReq setHTTPBody:myRequestData];
return urlReq;
}
以上就是本功能實(shí)現(xiàn)的思路及代碼。
遇到的坑:
由于我們后臺(tái)一次數(shù)據(jù)流只支持單張圖片上傳乎婿,所以沒(méi)貼多張的代碼测僵,有需要的小伙伴可以去這里
溫馨提示: 上面代碼是基于公司基礎(chǔ)庫(kù)實(shí)現(xiàn)的,所以可能非我們公司的小伙伴直接拿來(lái)用的話會(huì)報(bào)錯(cuò)谢翎,建議根據(jù)思路自己修改部分內(nèi)容