拿走即用之afn封装(OC版)

afn封装

  • 一旦AFN有较大的变动,用到AFN的项目需要更改很多的地方,为了避免这种情况,一般会对AFN封装出一个类,这样有了变动之后,只需要更改这个类即可(代码如下)

.h文件

#import 

typedef NS_ENUM(NSInteger, RequestMethod)
{
    post,
    get
};

@interface NetworkTools : NSObject

+ (instancetype)shareNetworkTools;

/**
 * requestMethod:请求方式
 * urlString:请求地址
 * parameters:请求参数
 * responseBlock:请求成功或失败的回调
 */

- (void)requestWithMethod:(RequestMethod)requestMethod andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock;

/**
 * data:上传资料
 * name:上传资料的名字
 * urlString:请求地址
 * parameters:请求参数
 * responseBlock:请求成功或失败的回调
 */

- (void)requestWithData:(NSData *)data andName:(NSString *)name andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock;

@end

.m文件

#import "NetworkTools.h"
#import 

@implementation NetworkTools

+ (instancetype)shareNetworkTools
{
    static NetworkTools *networkTools = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        networkTools = [[NetworkTools alloc] init];
    });
    return networkTools;
}

- (void)requestWithMethod:(RequestMethod)requestMethod andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock
{
    // 定义成功的block
    void (^success)(NSURLSessionDataTask *dataTask, id responseObject) = ^(NSURLSessionDataTask *dataTask,id responseObject)
    {
        responseBlock(responseObject, nil);
    };
    // 定义失败的block
    void (^failure)(NSURLSessionDataTask *dataTask,NSError *error) = ^(NSURLSessionDataTask *dataTask,NSError *error)
    {
        responseBlock(nil, error);
    };
    if (requestMethod == get) {
        [[AFHTTPSessionManager manager] GET:urlString parameters:parameters success:success failure:failure];
    } else {
        [[AFHTTPSessionManager manager] POST:urlString parameters:parameters success:success failure:failure];
    }
}

- (void)requestWithData:(NSData *)data andName:(NSString *)name andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock
{
    void (^success)(NSURLSessionDataTask *dataTask, id responseObject) = ^(NSURLSessionDataTask *dataTask,id responseObject)
    {
        responseBlock(responseObject, nil);
    };
    void (^failure)(NSURLSessionDataTask *dataTask,NSError *error) = ^(NSURLSessionDataTask *dataTask,NSError *error)
    {
        responseBlock(nil, error);
    };
    [[AFHTTPSessionManager manager] POST:urlString parameters:parameters constructingBodyWithBlock:^(id  _Nonnull formData) {
        [formData appendPartWithFileData:data name:name fileName:@"aa" mimeType:@"application/octet-stream"];
    } success:success failure:failure];
}

@end

你可能感兴趣的:(拿走即用之afn封装(OC版))