AFNetworking 封装

2020-11-18  本文已影响0人  陈先生的干货店

.h

#import <Foundation/Foundation.h>

/** 请求类型的枚举 */
typedef NS_ENUM(NSUInteger, MXEHttpRequestType){
    /** get请求 */
    MXEHttpRequestTypeGet = 0,
    /** post请求 */
    MXEHttpRequestTypePost
};

/**
 http通讯成功的block

 @param responseObject 返回的数据
 */
typedef void (^MXEHTTPRequestSuccessBlock)(id responseObject);

/**
 http通讯失败后的block

 @param error 返回的错误信息
 */
typedef void (^MXEHTTPRequestFailedBlock)(NSError *error);


//超时时间
extern NSInteger const kAFNetworkingTimeoutInterval;


@interface MXERequestService : NSObject

/**
 *  网络请求的实例方法
 *
 *  @param type         get / post (项目目前只支持这倆中)
 *  @param urlString    请求的地址
 *  @param parameters   请求的参数
 *  @param successBlock 请求成功回调
 *  @param failureBlock 请求失败回调
 */
+ (void)requestWithType:(MXEHttpRequestType)type
              urlString:(NSString *)urlString
             parameters:(NSDictionary *)parameters
           successBlock:(MXEHTTPRequestSuccessBlock)successBlock
           failureBlock:(MXEHTTPRequestFailedBlock)failureBlock;

/**
 取消队列
 */
+(void)cancelDataTask;

NS_ASSUME_NONNULL_BEGIN



+ (void)postRequestWithApi:(NSString *)api
                     param:(NSDictionary *)param
                   success:(void(^)(NSDictionary *rootDict))success
                   failure:(void(^)(id error))failure;

+ (void)getRequestWithApi:(NSString *)api
                    param:(NSDictionary *)param
                  success:(void(^)(NSDictionary *rootDict))success
                  failure:(void(^)(id error))failure;

@end

.m

NSInteger const kAFNetworkingTimeoutInterval = 10;

@implementation MXERequestService

static AFHTTPSessionManager *aManager;

+ (AFHTTPSessionManager *)sharedAFManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        aManager = [AFHTTPSessionManager manager];
        //以下三项manager的属性根据需要进行配置
        aManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/xml",@"text/json",@"text/plain",@"text/JavaScript",@"application/json",@"image/jpeg",@"image/png",@"application/octet-stream",nil];
        
        aManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        // 设置超时时间
        aManager.requestSerializer.timeoutInterval = kAFNetworkingTimeoutInterval;
    });
    return aManager;
}

+ (void)requestWithType:(MXEHttpRequestType)type
              urlString:(NSString *)urlString
             parameters:(NSDictionary *)parameters
           successBlock:(MXEHTTPRequestSuccessBlock)successBlock
           failureBlock:(MXEHTTPRequestFailedBlock)failureBlock {
    if (urlString == nil) {
        return;
    }
    
    if (@available(iOS 9.0, *)) {
        urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }else {
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    
    if (type == MXEHttpRequestTypeGet){
        [[self sharedAFManager] GET:urlString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (successBlock){
                id JSON =  [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                successBlock(JSON);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (error.code !=-999) {
                if (failureBlock) {
                    failureBlock(error);
                }
            }else{
                NSLog(@"取消队列了");
            }
        }];
    }
    if (type == MXEHttpRequestTypePost){
        
        [[self sharedAFManager] POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            id JSON =  [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if (successBlock){
                successBlock(JSON);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (error.code !=-999) {
                if (failureBlock){
                    failureBlock(error);
                }
            }else{
                NSLog(@"取消队列了");
            }
        }];
    }
}

+ (void)cancelDataTask {
    NSMutableArray *dataTasks = [NSMutableArray arrayWithArray:[self sharedAFManager].dataTasks];
    for (NSURLSessionDataTask *taskObj in dataTasks) {
        [taskObj cancel];
    }
}


+ (void)postRequestWithApi:(NSString *)api
                     param:(NSDictionary *)param
                   success:(void (^)(NSDictionary * _Nonnull))success
                   failure:(void (^)(id _Nonnull))failure {
    [self requestWithType:MXEHttpRequestTypePost urlString:api parameters:param successBlock:^(id responseObject) {
        success(responseObject);
    } failureBlock:^(NSError *error) {
        failure(error);
    }];
}

+ (void)getRequestWithApi:(NSString *)api
                    param:(NSDictionary *)param
                  success:(void (^)(NSDictionary * _Nonnull))success
                  failure:(void (^)(id _Nonnull))failure {
    [self requestWithType:MXEHttpRequestTypeGet urlString:api parameters:param successBlock:^(id responseObject) {
        success(responseObject);
    } failureBlock:^(NSError *error) {
        failure(error);
    }];
}

+ (void)downloadRequestWithApi:(NSString *)url
                    param:(NSDictionary *)param
                      progress:(void(^)(NSInteger progress))progress
                  success:(void(^)(NSDictionary *rootDict))success
                  failure:(void(^)(id error))failure{
    NSURLRequest *requset = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [[self sharedAFManager] downloadTaskWithRequest:requset progress:^(NSProgress * _Nonnull downloadProgress) {
//        progress(downloadProgress.);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
    }];
}

@end

上一篇下一篇

猜你喜欢

热点阅读