代码改变世界

iOS - 基于AFN的工具类以及多张图片上传的封装

2017-02-15 11:29  菜鸟Alex  阅读(1299)  评论(0编辑  收藏  举报

第一步

  • 首选创建管理者单利HBManager.h文件:
  • 参数arrDataarrName后面会讲到
  • +(void)resetArrDataAndArrName;后面会讲到

#import <AFNetworking/AFNetworking.h>

@interface HBManager : AFHTTPSessionManager

@property (strong, nonatomic) NSArray * arrData;
@property (strong, nonatomic) NSArray * arrName;
/* 图片上传成功 或者 失败 都必须调用此方法来重置数组,否则出错 */
+(void)resetArrDataAndArrName;

+(instancetype)sharedManager;

@end


  • HBManager.m文件
  • 实现单利方法.设置acceptableContentTypes属性
  • 实现+(void)resetArrDataAndArrName方法,不管上传成功还是失败都要调用来重置要上传的图片数组,以及图片名称数组

#import "HBManager.h"

@implementation HBManager

+(instancetype)sharedManager{

    static HBManager * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[HBManager alloc] init];
    });
    return instance;
}

-(instancetype)init{

    //[NSSet setWithObjects:@"application/json",@"text/plain",@"charset=utf-8", nil];
    if (self = [super init]) {
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"charset=utf-8", nil];
    }
    return self;
}

+(void)resetArrDataAndArrName{

    [HBManager sharedManager].arrName = nil;
    [HBManager sharedManager].arrData = nil;
}

@end

第二步

  • 创建工具类HBNetTool.hpost我们公司全部要求post:

#import <AFNetworking/AFNetworking.h>
#import "HBManager.h"
NS_ASSUME_NONNULL_BEGIN
@interface HBNetTool : NSObject




+ (void)POST:(NSString *)URLString
                             parameters:(nullable id)parameters progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
                                success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;

@end


NS_ASSUME_NONNULL_END


  • HBNetTool.m文件
  • 我们的参数要转换为json并以formData方式上传上去.我们服务端是.net
  • 上传多张图片拼接data,直接从刚才管理者哪里拿到图片data数组 以及 图片data数组对应的名字数组arrName通过 for 循环拼接.
  • 需要注意的是 图片数组 与 图片名称的数组一定要一一对应,一张图片对应一个名字.


#import "HBNetTool.h"


@implementation HBNetTool

+ (void)POST:(NSString *)URLString
                             parameters:(nullable id)parameters progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
                                success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                                failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure{

    [self POST:URLString parameters:parameters constructingBodyWithBlock:nil progress:uploadProgress success:success failure:failure];
    
}

+(NSURLSessionDataTask *)POST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id<AFMultipartFormData> _Nonnull))block progress:(void (^)(NSProgress * _Nonnull))uploadProgress success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure{

    HBManager * manager = [HBManager sharedManager];
    NSURLSessionDataTask * task = [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData * data = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
        [formData appendPartWithFormData:data name:@"data"];
        
        if (manager.arrData.count) {
            
            NSAssert([manager.arrData[0] isKindOfClass:[NSData class]] && (manager.arrData.count == manager.arrName.count), ([NSString stringWithFormat:@"%s  %s %zd arrData数组内必须存储NSData类型数据,arrName内部必须存储NSString类型数据并且arrData与arrName内部对象个数一样.",__FILE__,__FUNCTION__,__LINE__]));
            for (int i = 0; i < manager.arrData.count; i++) {
                
                [formData appendPartWithFileData:manager.arrData[i] name:manager.arrName[i] fileName:[NSString stringWithFormat:@"%@.jpg",manager.arrName[i]] mimeType:@"image/jpeg"];
            }
        }
        
    } progress:^(NSProgress * _Nonnull progress) {
        uploadProgress(progress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(task,responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(task,error);
    }];
    return task;
}

@end