Object-c重新封装AFNetworking改动

2019-12-19 17:57:45 浏览数 (3)

afn封装

  • 一旦AFN有较大的变动,用到AFN的项目需要更改很多的地方,为了避免这种情况,一般会对AFN封装出一个类,这样有了变动之后,只需要更改这个类即可(代码如下)
.h文件
代码语言:javascript复制
#import <Foundation/Foundation.h>

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文件

代码语言:javascript复制
#import "NetworkTools.h"
#import <AFNetworking.h>

@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<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:name fileName:@"aa" mimeType:@"application/octet-stream"];
    } success:success failure:failure];
}

@end

0 人点赞