美文网首页
iOS AFN关于form-data表单提交

iOS AFN关于form-data表单提交

作者: 冰棍儿好烫嘴 | 来源:发表于2021-03-10 15:53 被阅读0次

AFN对于表单提交,做了很好的封装,用起来也很方便,只是在iOS端用的很少,这里记录一下。

直接上代码:

+ (void)formDataPostMessageUrl:(NSString *)urlMessage WithDict:(NSDictionary *)parameters success:(void (^)(NSDictionary *result))successBlock fail:(void (^)())failBlock{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
 
//1、设置接收数据类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data" , @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];    

//2.设置form-data表单提交格式

    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
 //3.header添加基本信息--根据自己的app需要设置
   //添加设备
    NSString * uuid = [globalTools UDIDString];
    [manager.requestSerializer setValue:uuid forHTTPHeaderField:@"X-Device-Id"];
    //添加token
    NSString * token = [[NSUserDefaults standardUserDefaults] objectForKey:TOKEN];
    if (token.length>0) {
        [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
        
    }
    [manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"Device"];
    [manager.requestSerializer setValue:[globalTools appVersion] forHTTPHeaderField:@"Version"];

//发起请求
    [manager POST:urlMessage parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        for (NSString *key in parameters.allKeys) {
               // 循环拿到所有参数进行拼接
            NSString * searchStr = [parameters[key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
               [formData appendPartWithFormData:[searchStr dataUsingEncoding:NSUTF8StringEncoding] name:key];
           
    //如果有图片或者其他类型的数据,使用下面的函数:
    // [formData appendPartWithFileURL:@"url" name:@"参数名称" fileName:@"文件名称" mimeType:@"文件类型" error:nil];
            
    //     [formData appendPartWithFileData:data name:@"参数名称" fileName:@"文件名称" mimeType:@"文件类型"];
          
           }

    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            
            NSLog(@"%@", responseObject);
                   successBlock(responseDic);
               }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             if (failBlock) {
                 failBlock();
             }
    }];

    
}

相关文章

网友评论

      本文标题:iOS AFN关于form-data表单提交

      本文链接:https://www.haomeiwen.com/subject/mxvwqltx.html