iOS - 对AFNetworking的再次封装

在iOS的网络请求中,第三方框架 AFNetworking 对网络请求的封装程度已经很高了,但相对而言,对于有些许强迫症的我,还是试了一下再次封装.

网络请求成功时,responseObject为服务器返回的数据,successMsg为成功信息;

网络请求失败时,num为根据服务器返回的错误码,errorMsg为错误信息;

#import

//请求成功回调block

typedef void (^requestNewSuccessBlock) (NSDictionary *responseObject, NSString *successMsg);

//请求失败回调block

typedef void (^requestNewFailureBlock) (int num, NSString *errorMsg);

//请求方式

typedef enum {

    NewGET = 100,

    NewPOST,

    NewDelete,

    NewPut,

} HTTPNewMethod;

@interface CustomerNewSession : AFHTTPSessionManager

+ (instancetype)sharedSessionManager;

//新接口

- (void)requestWithNewMethod:(HTTPNewMethod)method

                    withPath:(NSString *)path

                  withParams:(NSDictionary *)params

            withSuccessBlock:(requestNewSuccessBlock)success

            withFailureBlock:(requestNewFailureBlock)failure;

@end


#import "CustomerNewSession.h"

@implementation CustomerNewSession

+ (instancetype)sharedSessionManager {

    static CustomerNewSession *manager = nil;

    static dispatch_once_t pred;

    dispatch_once(&pred, ^{

        manager = [[self alloc] initWithBaseURL:nil];

    });

    return manager;

}

- (instancetype)initWithBaseURL:(NSURL *)url {


    self = [super initWithBaseURL:url];


    if (self) {

        // 请求超时设定

        self.requestSerializer.timeoutInterval = networkTime;

        // 请求头设定

        [self.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];


        [self.requestSerializer setValue:@"2" forHTTPHeaderField:@"interface_version"];


        // 安全策略 - 无条件信任

        self.securityPolicy = [[AFSecurityPolicy alloc] init];

        [self.securityPolicy setAllowInvalidCertificates:YES];

        [self.securityPolicy setValidatesDomainName:NO];

    }


    return self;


}

- (void)requestWithNewMethod:(HTTPNewMethod)method

                    withPath:(NSString *)path

                  withParams:(NSDictionary *)params

            withSuccessBlock:(requestNewSuccessBlock)success

            withFailureBlock:(requestNewFailureBlock)failure

{


    //请求方式

    switch (method) {

        case NewGET:

        {

            [self GET:path parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {


                [self dealWithSuccessResponseObject:responseObject withSuccessBlock:success withFailBlock:failure];


            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {


                [self dealWithFailError:error withBlock:failure];


            }];

        }

            break;


        case NewPOST:

        {

            [self POST:path parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {


                [self dealWithSuccessResponseObject:responseObject withSuccessBlock:success withFailBlock:failure];


            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {


                [self dealWithFailError:error withBlock:failure];


            }];

        }

            break;


        case NewDelete:

        {

            [self DELETE:path parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {


                [self dealWithSuccessResponseObject:responseObject withSuccessBlock:success withFailBlock:failure];


            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {


                [self dealWithFailError:error withBlock:failure];


            }];

        }

            break;


        case NewPut:

        {

            [self PUT:path parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {


                [self dealWithSuccessResponseObject:responseObject withSuccessBlock:success withFailBlock:failure];


            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {


                [self dealWithFailError:error withBlock:failure];


            }];

        }

            break;


        default:

            break;


    }


}

//新接口 网络请求成功后执行 - 网络正常,有返回数据

- (void)dealWithSuccessResponseObject:(id _Nullable)responseObject withSuccessBlock:(requestNewSuccessBlock)success withFailBlock:(requestNewFailureBlock)failure {


    dispatch_async(dispatch_get_main_queue(), ^{


//        NSLog(@"%@",responseObject);


        int status = [[responseObject objectForKey:ResultStatus] intValue];

        NSString *message = [responseObject objectForKey:ResultMessage];


        switch (status) {


            case 100://成功

            {

                NSDictionary *dic = [responseObject objectForKey:ResultData];

                success(dic,message);

            }

                break;

            default://各种各样的失败

            {

                NSLog(@"新接口错误:%d == %@",status,message);

                failure(status, message);

            }

                break;


        }


    });


}

//网络请求失败后执行 - 网络异常

- (void)dealWithFailError:(NSError * _Nonnull)error withBlock:(requestNewFailureBlock)failure {


    dispatch_async(dispatch_get_main_queue(), ^{

        NSLog(@"新接口服务器错误:%@",error.localizedDescription);

        NSString *message = error.localizedDescription;

        if (message.length == 0) {

            message = LocalString(@"NetError");

        }

        failure(101, message);

    });

}

@end

你可能感兴趣的:(iOS - 对AFNetworking的再次封装)