iOS網路請求之上傳圖片:從示例到原始碼--以上傳回撥圖片為例 (AFNetworking、HYBNetworking、XMNetworking)

陳滿iOS發表於2018-07-29

前言

  • 網路框架

本文一開始上傳圖片以呼叫HYNetworking的API為例,這個網路框架是以AFNetworking為基礎進行的封裝。HYNetworking內部實現上傳圖片的時候,其實就是採用AFNetworking關於上傳圖片的API,都是AFNetworking裡面一個API。後面再講XMNetworking上傳圖片請求的操作方法,它也是基於AFNetworking上傳進行的封裝,不過比HYNetworking更加隱晦而已。

  • 需求背景

這裡的需求背景是,某app採用全球領先的AI方案提供商 -- 曠視科技 的Face++ SDK進行身份證識別:它識別到身份證後會回撥一個圖片資料,我們用此圖片向Face++公司的伺服器請求驗證,該請求通過則block回撥成功,接著將圖片資料儲存到手機本地,然後在合適的時機(比如,點選“完成”或者“下一步”按鈕)把圖片資料上傳到自己公司的伺服器。

  • 先上總結

上傳圖片的流程圖如下所示

上傳圖片流程圖

1. 獲取回撥圖片

下面舉例一個典型Face++的例子

  • 點選“掃描身份證按鈕”事件處理
// 身份證掃描正面
__weak typeof(self) weakSelf = self;
BOOL idcard = [MGIDCardManager getLicense];

if (!idcard) {
    [[[UIAlertView alloc] initWithTitle:@"提示" message:@"SDK授權失敗,請檢查" delegate:self cancelButtonTitle:@"完成" otherButtonTitles:nil, nil] show];
    return;
}

if ([CommonUtils isAllowedCamera] == NO) {
    
    //無許可權
    UIAlertController *AlertController = [UIAlertController alertControllerWithTitle:@"“小滿APP”想訪問您的相機" message:@"需要您的同意,才能訪問相機" preferredStyle:UIAlertControllerStyleAlert];
    
    [AlertController addAction:[UIAlertAction actionWithTitle:@"去設定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }]];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    //彈出提示框;
    [self presentViewController:AlertController animated:YES completion:nil];
    
    return;
}

MGIDCardManager *cardManager = [[MGIDCardManager alloc] init];

[cardManager IDCardStartDetection:weakSelf IdCardSide:IDCARD_SIDE_FRONT
                           finish:^(MGIDCardModel *model) {
                               
                               [_cardInfoVC sendFaceIDCardRequest:[model croppedImageOfIDCard]];
                           } errr:^(MGIDCardError) {
                               
                           }];
複製程式碼
#pragma mark - Return UIImage
- (UIImage *)croppedImageOfIDCard {
#if TARGET_IPHONE_SIMULATOR
    return nil;
#else
    return [self.result croppedImageOfIDCard];
#endif
}
複製程式碼
  • Face++SDK本地識別成功後,攜帶image向Face++後臺請求程式碼(主要檢驗身份證合法性等等),請求成功之後我們才將身份證圖片儲存到本地:
- (void)sendFaceIDCardRequest:(UIImage *)image
{
    [KVNProgress showWithParameters:@{KVNProgressViewParameterStatus: @"載入中...",
                                      KVNProgressViewParameterBackgroundType: @(KVNProgressBackgroundTypeSolid),
                                      KVNProgressViewParameterFullScreen: @(NO)}];
    
    UIImage *cardImage = image;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:api_key forKey:@"api_key"];
    [params setObject:api_secret forKey:@"api_secret"];
    [params setObject:@"1" forKey:@"legality"];

    __weak typeof(self) weakSelf = self;
    [HYBNetworking uploadWithImage:cardImage url:QueryCardId filename:@"image"
    name:@"image" mimeType:@"image/jpeg" parameters:params progress:^(int64_t bytesWritten, int64_t totalBytesWritten) {}
    success:^(id response) {
        
        [KVNProgress dismiss];
        NSDictionary *dic = response;
        NSLog(@"%@",[dic mj_JSONString]);


        NSDictionary *legalityDict = [dic objectForKey:@"legality"];
        NSString *side = [dic objectForKey:@"side"];    
        if ([side isEqualToString:@"back"]) {
            
            // 發證機關
            self.cell.CREDITISSUEQRG = [dic objectForKey:@"issued_by"];
            // valid_date 證件到期日
            self.cell.CREDITCERTENDTIME  = [dic objectForKey:@"valid_date"];
            [weakSelf saveImage:image withName:@"reverseCardImage.png"];
            
            weakSelf.cell.reverseCardImage = image;
            [weakSelf.cell setClipReverseCardImage:image];
            [weakSelf.cell setReverseCardImageDataInfo:legalityDict];
            
        }
        else if ([side isEqualToString:@"front"]) {
            
            // 姓名
            weakSelf.cell.nameTextField.text = [dic objectForKey:@"name"];
            // 性別
            //NSString *SEX = [dic objectForKey:@"race"];
            // 證件號碼
            weakSelf.cell.IDCardTextField.text = [dic objectForKey:@"id_card_number"];
            // 戶籍所在地
            weakSelf.cell.HOUSEHOLDADDR = [dic objectForKey:@"address"];
            
            NSString *CERTID = [CommonUtils getValueInUDWithKey:kCERTID];
            if (![CommonUtils isStringNilOrEmpty:CERTID]) {
                if (![CERTID isEqualToString:[dic objectForKey:@"id_card_number"]]) {
                    [Toast showBottomWithText:@"您使用的身份證與您實名的身份證不一致"];
                    return;
                }
            }
            // 更新UI
            weakSelf.cell.positiveIDCardImage = image;//載入圖片
            [weakSelf.cell setClipPositiveIDCardImage:image];
            [weakSelf.cell setPositiveIDCardImageDataInfo:legalityDict];
            
            // 出生年月
//            NSDictionary *dict = [dic objectForKey:@"birthday"];
//            NSString *day = [dict objectForKey:@"day"];
//            NSString *month = [dict objectForKey:@"month"];
//            NSString *year = [dict objectForKey:@"year"];
            
            [weakSelf saveImage:image withName:@"positiveIDCardImage.png"];
        }
        
    } fail:^(NSError *error) {
        [KVNProgress dismiss];
        [Toast showBottomWithText:kNetworkErrorMsg];
    }];
}
複製程式碼
  • 最後面有個saveImage: withName:就是向Face++請求成功之後,進行儲存到本地操作。
#pragma mark - 儲存圖片至沙盒
- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    if ([imageName isEqualToString:@"positiveIDCardImage.png"]) {
        NSString *imgPath = [CommonUtils pathFileDocDir:@"/BorrowProcess/positiveIDCardImage.png"];
        if ([CommonUtils fileExistAtPath:imgPath]) {
            [CommonUtils fileDel:imgPath];
        }
    }
    if ([imageName isEqualToString:@"reverseCardImage.png"]) {
        NSString *imgPath1 = [CommonUtils pathFileDocDir:@"/BorrowProcess/reverseCardImage.png"];
        if ([CommonUtils fileExistAtPath:imgPath1]) {
            [CommonUtils fileDel:imgPath1];
        }
    }
    
    float kCompressionQuality = 0.5;
    NSData *imageData = UIImageJPEGRepresentation(currentImage, kCompressionQuality);  //將圖片壓縮
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/BorrowProcess/"] stringByAppendingPathComponent:imageName];  //獲取沙盒目錄
    
    //建立資料夾
    [self createFile];
    //儲存圖片
    BOOL _isWriteToFile = [imageData writeToFile:fullPath atomically:YES];  //將圖片寫入檔案
}
複製程式碼

2. 上傳回撥圖片

通過上面的儲存操作,現在我們的APP到了點選下一步的情形,這時候需要我們向自己的後臺(不是Face++的後臺)上傳圖片了。

2.1 呼叫HYBNetworking的上傳圖片API

上傳圖片API

+ (HYBURLSessionTask *)uploadWithImage:(UIImage *)image
                                   url:(NSString *)url
                              filename:(NSString *)filename
                                  name:(NSString *)name
                              mimeType:(NSString *)mimeType
                            parameters:(NSDictionary *)parameters
                              progress:(HYBUploadProgress)progress
                               success:(HYBResponseSuccess)success
                                  fail:(HYBResponseFail)fail 
複製程式碼

呼叫示例

#pragma mark - 上傳身份證正面
//請求介面
-(void)httpRequestFRONT{
    NSString *LOANAPPLICATIONNO = nil;
    NSMutableArray *dataArray = [self seekPlist];
    if (dataArray) {
        NSDictionary *dataDict = nil;
        for (NSDictionary *dict in dataArray) {
            NSInteger index = [[dict objectForKey:@"index"] integerValue];
            if (index == 0) {
                if (dict) {
                    dataDict = dict;
                }
            }
        }
        
        NSDictionary *dd = [dataDict objectForKey:@"BorrowProcess"];
        LOANAPPLICATIONNO = [dd objectForKey:@"LOANAPPLICATIONNO"];
    }
    if ([CommonUtils isStringNilOrEmpty:LOANAPPLICATIONNO]) {
        LOANAPPLICATIONNO = @"";
    }
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *fileName = @"positiveIDCardImage";
    NSString *filePath = [NSString stringWithFormat:@"%@/BorrowProcess/%@.png", path, fileName];
    UIImage *image;
    if ([self isFileExist:fileName] == YES)
    {
        //顯示本地快取
        image = [UIImage imageWithContentsOfFile:filePath];
        
    }
    [CommonUtils saveStrValueInUD:@"status016" forKey:kTRANSCODE];
    
    [KVNProgress showWithParameters:@{KVNProgressViewParameterStatus: @"載入中...",
                                      KVNProgressViewParameterBackgroundType: @(KVNProgressBackgroundTypeSolid),
                                      KVNProgressViewParameterFullScreen: @(NO)}];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    
    [params setObject:[CommonUtils getStrValueInUDWithKey:kTOKEN] forKey:@"TOKEN"];
    // 使用者賬號
    [params setObject:[CommonUtils getStrValueInUDWithKey:kUSERNO] forKey:@"USERNO"];
    
    
    //    NSArray *BUSINESSTYPE = @[];//文件編號
    //    NSArray *BUSINESSNO = @[];//業務編號
    //    NSArray *DOCTYPE = @[];//文件型別
    [params setObject:@"LOAN_APPLY" forKey:@"BUSINESSTYPE"];
    [params setObject:LOANAPPLICATIONNO forKey:@"BUSINESSNO"];
    [params setObject:@"IDCARD_FRONT_APP" forKey:@"DOCTYPE"];
    
    __weak typeof(self) weakSelf = self;
    
    //上傳圖片
    [HYBNetworking uploadWithImage:image url:uploadImage filename:@"IDFrontImage.jpg" name:@"FILE" mimeType:@"image/jpeg" parameters:params progress:^(int64_t bytesWritten, int64_t totalBytesWritten) {
        //獲取進度:bytesWritten/totalBytesWritten

    } success:^(id response) {
        
        [KVNProgress dismiss];
        
        typeof(weakSelf) strongSelf = weakSelf;
        NSString *stringData = [response mj_JSONString];
        stringData = [DES3Util decrypt:stringData];
        NSLog(@"stirngData: %@", stringData);
        
        NSDictionary *responDict = [stringData mj_JSONObject];
        NSString *RETCODE = [responDict objectForKey:@"RETCODE"];
        if ([RETCODE isEqualToString:kSUCCESS]) {
            
            [strongSelf httpRequestBACK];
        }else if([RETCODE isEqualToString:kROKEN]){
            NSDictionary *processdict = @{@"index":[NSNumber numberWithInteger:10], @"showProcessView":[NSNumber numberWithBool:YES]};
            [[NSNotificationCenter defaultCenter] postNotificationName:kBorrowProcessNotication object:nil userInfo:processdict];
        }else{
            NSString *RETMSG = [responDict objectForKey:@"RETMSG"];
            if (![CommonUtils isStringNilOrEmpty:RETMSG]) {
                [Toast showBottomWithText:RETMSG];
            }
        }
    } fail:^(NSError *error) {
        [KVNProgress dismiss];
        [Toast showBottomWithText:kNetworkErrorMsg];
    }];
}
複製程式碼

2.2 呼叫AFNetwork整合圖片的API -- 暨HYBNetworing上傳圖片封裝原始碼解析

整合圖片API

- (void)appendPartWithFileData:(NSData *)data
                          name:(NSString *)name
                      fileName:(NSString *)fileName
                      mimeType:(NSString *)mimeType
複製程式碼

呼叫示例 -- 上述2.1節中HYBNetworking的上傳圖片其實是呼叫AFNetworking的上傳圖片API。所以,HYBNetworking框架中上傳圖片的原始碼實現就是呼叫AFNetworking上傳圖片API的一個示例:

  • HYBNetworking.m
+ (HYBURLSessionTask *)uploadWithImage:(UIImage *)image
                                   url:(NSString *)url
                              filename:(NSString *)filename
                                  name:(NSString *)name
                              mimeType:(NSString *)mimeType
                            parameters:(NSDictionary *)parameters
                              progress:(HYBUploadProgress)progress
                               success:(HYBResponseSuccess)success
                                  fail:(HYBResponseFail)fail {
  if ([self baseUrl] == nil) {
    if ([NSURL URLWithString:url] == nil) {
      HYBAppLog(@"URLString無效,無法生成URL。可能是URL中有中文,請嘗試Encode URL");
      return nil;
    }
  } else {
    if ([NSURL URLWithString:[NSString stringWithFormat:@"%@%@", [self baseUrl], url]] == nil) {
      HYBAppLog(@"URLString無效,無法生成URL。可能是URL中有中文,請嘗試Encode URL");
      return nil;
    }
  }
  
  if ([self shouldEncode]) {
    url = [self encodeUrl:url];
  }
  
  NSString *absolute = [self absoluteUrlWithPath:url];
  
  AFHTTPSessionManager *manager = [self manager];
  HYBURLSessionTask *session = [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    
    NSString *imageFileName = filename;
    if (filename == nil || ![filename isKindOfClass:[NSString class]] || filename.length == 0) {
      NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
      formatter.dateFormat = @"yyyyMMddHHmmss";
      NSString *str = [formatter stringFromDate:[NSDate date]];
      imageFileName = [NSString stringWithFormat:@"%@.jpg", str];
    }
    
    // 整合圖片,以檔案流的格式
    [formData appendPartWithFileData:imageData name:name fileName:imageFileName mimeType:mimeType];

  } progress:^(NSProgress * _Nonnull uploadProgress) {
    if (progress) {
      progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
    }
  } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    [[self allTasks] removeObject:task];
    [self successResponse:responseObject callback:success];
    
    if ([self isDebug]) {
      [self logWithSuccessResponse:responseObject
                               url:absolute
                            params:parameters];
    }
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    [[self allTasks] removeObject:task];
    
    [self handleCallbackWithError:error fail:fail];
    
    if ([self isDebug]) {
      [self logWithFailError:error url:absolute params:nil];
    }
  }];
  
  [session resume];
  if (session) {
    [[self allTasks] addObject:session];
  }
  
  return session;
}
複製程式碼

可見,整合圖片的一句關鍵程式碼在

// 整合圖片,以檔案流的格式
[formData appendPartWithFileData:imageData name:name fileName:imageFileName mimeType:mimeType];
複製程式碼

這裡是設定圖片的資料流,作為AFNetwork的POST請求方法的一個constructingBodyWithBlock引數的輸入。

AFNetwork的POST請求方法原始碼

  • AFHTTPSessionManager.m
- (NSURLSessionDataTask *)POST:(NSString *)URLString
                    parameters:(id)parameters
     constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                      progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    NSError *serializationError = nil;
    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
    if (serializationError) {
        if (failure) {
            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
                failure(nil, serializationError);
            });
        }

        return nil;
    }

    __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
        if (error) {
            if (failure) {
                failure(task, error);
            }
        } else {
            if (success) {
                success(task, responseObject);
            }
        }
    }];

    [task resume];

    return task;
}
複製程式碼

這個方法將block傳遞給下一個API,並返回一個request:

  • AFURLRequestSerialization.m
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
                                              URLString:(NSString *)URLString
                                             parameters:(NSDictionary *)parameters
                              constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                                                  error:(NSError *__autoreleasing *)error
{
    NSParameterAssert(method);
    NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);

    NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error];

    __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];

    if (parameters) {
        for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
            NSData *data = nil;
            if ([pair.value isKindOfClass:[NSData class]]) {
                data = pair.value;
            } else if ([pair.value isEqual:[NSNull null]]) {
                data = [NSData data];
            } else {
                data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
            }

            if (data) {
                [formData appendPartWithFormData:data name:[pair.field description]];
            }
        }
    }

    if (block) {
        block(formData);
    }

    return [formData requestByFinalizingMultipartFormData];
}
複製程式碼
  • 這個方法的關鍵在於最後,用block回撥了formData:
if (block) {
        block(formData);
    }
複製程式碼

這個formData是一個AFStreamingMultipartFormData模型的物件

圖片模型 -- AFStreamingMultipartFormData

  • AFURLRequestSerialization.m
@interface AFStreamingMultipartFormData ()
@property (readwrite, nonatomic, copy) NSMutableURLRequest *request;
@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
@property (readwrite, nonatomic, copy) NSString *boundary;
@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream;
@end
複製程式碼

這樣,就執行了前面呼叫時block裡面的圖片資料整合操作([formData appendPartWithFileData...];)。

圖片資料整合操作

multipartFormRequestWithMethod:...的實現程式碼中,接著,利用block體中設定好的formData,呼叫下述的requestByFinalizingMultipartFormData方法以返回一個request,然後進行請求。requestByFinalizingMultipartFormData的程式碼如下:

  • AFURLRequestSerialization.m
- (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
    if ([self.bodyStream isEmpty]) {
        return self.request;
    }

    // Reset the initial and final boundaries to ensure correct Content-Length
    [self.bodyStream setInitialAndFinalBoundaries];
    [self.request setHTTPBodyStream:self.bodyStream];

    [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"];
    [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"];

    return self.request;
}
複製程式碼

上面程式碼的關鍵在於將圖片資料整合進request,設定HTTPBodyStream,即[self.request setHTTPBodyStream:self.bodyStream];

  • 獲取上述request之後,如前面所述“ AFNetwork的POST請求方法原始碼”,呼叫返回request的API之後,再呼叫POST請求方法進行請求操作,即__block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {這一句。

獲取帶有圖片request的API

- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
                                              URLString:(NSString *)URLString
                                             parameters:(NSDictionary *)parameters
                              constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                                                  error:(NSError *__autoreleasing *)error
複製程式碼

上傳帶有圖片request的API

- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
                                                 progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
                                        completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
複製程式碼

2.3 原始碼分析 -- AFNetwork整合圖片資料呼叫棧解析

  • 將描述圖片的引數字串轉化頭字典
- (void)appendPartWithFileData:(NSData *)data
                          name:(NSString *)name
                      fileName:(NSString *)fileName
                      mimeType:(NSString *)mimeType
{
    NSParameterAssert(name);
    NSParameterAssert(fileName);
    NSParameterAssert(mimeType);

    NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
    [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
    [mutableHeaders setValue:mimeType forKey:@"Content-Type"];

    [self appendPartWithHeaders:mutableHeaders body:data];
}
複製程式碼
  • 為圖片資料新增頭字典 -- 資料整合
- (void)appendPartWithHeaders:(NSDictionary *)headers
                         body:(NSData *)body
{
    NSParameterAssert(body);

    AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
    bodyPart.stringEncoding = self.stringEncoding;
    bodyPart.headers = headers;
    bodyPart.boundary = self.boundary;
    bodyPart.bodyContentLength = [body length];
    bodyPart.body = body;

    [self.bodyStream appendHTTPBodyPart:bodyPart];
}
複製程式碼

其中,資料流self.bodyStream是這樣定義的:

@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream;
複製程式碼

其中,AFMultipartBodyStream是這樣定義的:

@interface AFMultipartBodyStream : NSInputStream <NSStreamDelegate>
複製程式碼
  • 再來看看怎樣向資料流新增整合好的圖片資料的:
- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart {
    [self.HTTPBodyParts addObject:bodyPart];
}
複製程式碼
  • 其中,HTTPBodyParts是這樣定義的:
@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts;
複製程式碼
  • 另外,AFHTTPBodyPart的定義是這樣的:
@interface AFHTTPBodyPart : NSObject
@property (nonatomic, assign) NSStringEncoding stringEncoding;
@property (nonatomic, strong) NSDictionary *headers;
@property (nonatomic, copy) NSString *boundary;
@property (nonatomic, strong) id body;
@property (nonatomic, assign) unsigned long long bodyContentLength;
@property (nonatomic, strong) NSInputStream *inputStream;

@property (nonatomic, assign) BOOL hasInitialBoundary;
@property (nonatomic, assign) BOOL hasFinalBoundary;

@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable;
@property (readonly, nonatomic, assign) unsigned long long contentLength;
複製程式碼

3. XMNetworking

XMNetworking其實也是基於ANNetworking封裝的,不過封裝的層級比HYBNetworking多,看起來有點隱晦。這裡分析一下XMNetworking上傳圖片的API。

3.1 整合圖片

  • 整合圖片API
- (void)addFormDataWithName:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType fileData:(NSData *)fileData 
複製程式碼
  • 呼叫示例
- (NSString *_Nullable)uploadWithUploadImageModels:(nullable NSArray<UploadImageModel *> *)imageModelArr params:(id _Nullable )params paramsType:(ParamsType)paramsType userNo:(NSString *)userNo APITag:(API_Tag)tag mimeType:(nullable NSString *)mimeType
       OnSuccess:(SuccessBlock)successBlock onFailure:(FailureBlock)failureBlock
{
    NSString *identifier = [XMCenter sendRequest:^(XMRequest * _Nonnull request) {
        
        request.api = [self pathURLWithAPITag:tag];
        
        if ([self respondsToSelector:@selector(cys_requestOnlyLayerParameters:)]) {
            request.parameters = [self cys_requestOnlyLayerParameters:params];
        }
        
        // 上傳圖片,以檔案流的格式
        for (UploadImageModel *imageModel in imageModelArr) {
            NSData *imageData = UIImageJPEGRepresentation(imageModel.image, 0.5);
            
            NSString *imageFileName = imageModel.fileName;
            if (imageModel.fileName == nil || ![imageModel.fileName isKindOfClass:[NSString class]] || imageModel.fileName.length == 0) {
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmmss";
                NSString *str = [formatter stringFromDate:[NSDate date]];
                imageFileName = [NSString stringWithFormat:@"%@.jpg", str];
            }
            // 上傳圖片
            [request addFormDataWithName:imageModel.name fileName:imageFileName mimeType:mimeType fileData:imageData];
        }
        
        NSLog(@"請求的引數:%@",request.parameters);
        if (imageModelArr.count > 0) {
            request.requestType = kXMRequestUpload;
        }
        request.requestSerializerType = kXMRequestSerializerJSON;
    } onSuccess:^(id  _Nullable responseObject) {
        // 省略...
複製程式碼

3.2 上傳圖片API原始碼解析

  • 將整合好的圖片資料formData新增到圖片模型陣列uploadFormDatas
- (void)addFormDataWithName:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType fileData:(NSData *)fileData {
    
    
    XMUploadFormData *formData = [XMUploadFormData formDataWithName:name fileName:fileName mimeType:mimeType fileData:fileData];
    [self.uploadFormDatas addObject:formData];
}
複製程式碼
  • 整合圖片資料
+ (instancetype)formDataWithName:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType fileData:(NSData *)fileData {
    XMUploadFormData *formData = [[XMUploadFormData alloc] init];
    formData.name = name;
    formData.fileName = fileName;
    formData.mimeType = mimeType;
    formData.fileData = fileData;
    return formData;
}
複製程式碼
  • 圖片模型陣列
- (NSMutableArray<XMUploadFormData *> *)uploadFormDatas {
    if (!_uploadFormDatas) {
        _uploadFormDatas = [NSMutableArray array];
    }
    return _uploadFormDatas;
}
複製程式碼
  • 圖片模型 -- XMUploadFormData
/**
 `XMUploadFormData` is the class for describing and carring the upload file data, see `AFMultipartFormData` protocol for details.
 */
@interface XMUploadFormData : NSObject

/**
 The name to be associated with the specified data. This property must not be `nil`.
 */
@property (nonatomic, copy) NSString *name;

/**
 The file name to be used in the `Content-Disposition` header. This property is not recommended be `nil`.
 */
@property (nonatomic, copy, nullable) NSString *fileName;

/**
 The declared MIME type of the file data. This property is not recommended be `nil`.
 */
@property (nonatomic, copy, nullable) NSString *mimeType;

/**
 The data to be encoded and appended to the form data, and it is prior than `fileURL`.
 */
@property (nonatomic, strong, nullable) NSData *fileData;

/**
 The URL corresponding to the file whose content will be appended to the form, BUT, when the `fileData` is assigned,the `fileURL` will be ignored.
 */
@property (nonatomic, strong, nullable) NSURL *fileURL;

// NOTE: Either of the `fileData` and `fileURL` should not be `nil`, and the `fileName` and `mimeType` must both be `nil` or assigned at the same time,
複製程式碼
  • 遍歷圖片模型陣列中的圖片模型進行上傳請求
- (void)xm_uploadTaskWithRequest:(XMRequest *)request
               completionHandler:(XMCompletionHandler)completionHandler {
    
    AFHTTPSessionManager *sessionManager = [self xm_getSessionManager:request];
    AFHTTPRequestSerializer *requestSerializer = [self xm_getRequestSerializer:request];
    
    __block NSError *serializationError = nil;
    NSMutableURLRequest *urlRequest = [requestSerializer multipartFormRequestWithMethod:@"POST"
                                                                              URLString:request.url
                                                                             parameters:request.parameters
                                                              constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [request.uploadFormDatas enumerateObjectsUsingBlock:^(XMUploadFormData *obj, NSUInteger idx, BOOL *stop) {
            if (obj.fileData) {
                if (obj.fileName && obj.mimeType) {
                    [formData appendPartWithFileData:obj.fileData name:obj.name fileName:obj.fileName mimeType:obj.mimeType];
                } else {
                    [formData appendPartWithFormData:obj.fileData name:obj.name];
                }
            } else if (obj.fileURL) {
                NSError *fileError = nil;
                if (obj.fileName && obj.mimeType) {
                    [formData appendPartWithFileURL:obj.fileURL name:obj.name fileName:obj.fileName mimeType:obj.mimeType error:&fileError];
                } else {
                    [formData appendPartWithFileURL:obj.fileURL name:obj.name error:&fileError];
                }
                if (fileError) {
                    serializationError = fileError;
                    *stop = YES;
                }
            }
        }];
    } error:&serializationError];
    
    if (serializationError) {
        if (completionHandler) {
            dispatch_async(xm_request_completion_callback_queue(), ^{
                completionHandler(nil, serializationError);
            });
        }
        return;
    }
    
    [self xm_processURLRequest:urlRequest byXMRequest:request];
    
    NSURLSessionUploadTask *uploadTask = nil;
    __weak __typeof(self)weakSelf = self;
    uploadTask = [sessionManager uploadTaskWithStreamedRequest:urlRequest
                                                           progress:request.progressBlock
                                                  completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf xm_processResponse:response
                                object:responseObject
                                 error:error
                               request:request
                     completionHandler:completionHandler];
    }];
    
    [self xm_setIdentifierForReqeust:request taskIdentifier:uploadTask.taskIdentifier sessionManager:sessionManager];
    [uploadTask bindingRequest:request];
    [uploadTask resume];
}
複製程式碼
  • 可見,XMNetworking最後還是呼叫AFNetwork的POST請求及uploadTaskWithStreamedRequest方法進行上傳。
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
                                              URLString:(NSString *)URLString
                                             parameters:(NSDictionary *)parameters
                              constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                                                  error:(NSError *__autoreleasing *)error
複製程式碼
  • 同樣可見,同HYBNetwork一樣,呼叫AFNetwork的圖片資料整合API appendPartWithFileData:進行設定
[formData appendPartWithFileData:obj.fileData name:obj.name fileName:obj.fileName mimeType:obj.mimeType];
複製程式碼

4. 總結:上傳圖片邏輯整理

AFNetworking

  • 壓縮轉換:UIImage例項物件通過UIImageJPEGRepresentation壓縮轉換為NSData,下面稱之為imageData。
  • 資訊整合:將imageData與檔名fileName,檔案路徑name,型別名mimeType整合成圖片模型(AFHTTPBodyPart)的一個物件bodyPart中去。
  • 新增圖片模型:將上面新建好的圖片模型物件bodyPart,向圖片輸入流(AFMultipartBodyStream)的物件bodyStream的陣列屬性(HTTPBodyParts)新增。
  • 設定requet的HTTPBodyStream屬性為bodyStream:封裝為requestByFinalizingMultipartFormData
  • 將圖片模型物件formData用AFNetwork的POST請求與uploadTaskWithStreamedRequest方法進行上傳。

HYBNetworking

  • 壓縮轉換:UIImage例項物件通過UIImageJPEGRepresentation壓縮轉換為NSData,下面稱之為imageData。
  • 資訊整合:利用AFNetwork的appendPartWithFileData,將imageData與檔名fileName,檔案路徑name,型別名mimeType整合成圖片模型(AFStreamingMultipartFormData)的一個物件formData中去。
  • 將圖片模型物件formData用AFNetwork的POST請求與uploadTaskWithStreamedRequest方法進行上傳。

XMNetworking

  • 壓縮轉換:UIImage例項物件通過UIImageJPEGRepresentation壓縮轉換為NSData,下面稱之為imageData。
  • 資訊整合:利用AFNetwork的appendPartWithFileData,將imageData與檔名fileName,檔案路徑name,型別名mimeType整合成圖片模型(XMUploadFormData)的一個物件formData中去。
  • 新增圖片模型:向管理器的圖片模型陣列uploadFormDatas新增上面新建好的圖片模型物件formData。
  • 遍歷圖片模型陣列,獲得圖片模型,利用AFNetwork的POST請求與uploadTaskWithStreamedRequest方法進行上傳。

5. 說明

本文示例只做了最簡單的請求方式 -- 發起一次請求就呼叫一次。

其實,還有很多可以優化的點,例如,對所有request進行管理封裝:建立一個請求的佇列或者陣列,相同請求不允許再新增,優先順序低的請求先等待,非同步請求的最大併發執行緒數,等等。這裡只提醒,就不介紹了。

相關文章