基于AFN的网络库封装

第一层 HMRequest 功能

  • HTTP 常用请求方式 GET POST PUT PATCH DELETE
  • POST 上传JSON数据
  • PHOTO 单张多张照片上传

HMRequest.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@interface HMRequestModel : HMBaseModel
@property (nonatomic, strong) NSNumber *code;
@property (nonatomic, copy) NSString   *message;

@end

typedef void(^HMRequestSuccessBlock)(id result, HMRequestModel *model);
typedef void(^HMRequestFailureBlock)(NSString *msg);

typedef NS_ENUM(NSInteger, HMRequestMethod) {
    HTTP_REQUEST_TYPE_GET    = 0,
    HTTP_REQUEST_TYPE_POST   = 1,
    HTTP_REQUEST_TYPE_PUT    = 2,
    HTTP_REQUEST_TYPE_PATCH  = 3,
    HTTP_REQUEST_TYPE_DELETE = 4,
};

typedef NS_ENUM(NSInteger, HMRequestStatus) {
    HTTP_REQUEST_STATUS_FAILURE = -1,
    HTTP_REQUEST_STATUS_SUCCESS = 0
};

@interface HMRequest : NSObject

#pragma mark- http request
+ (void)hm_requestActionWithUrl:(NSString *)url
                         params:(NSDictionary *)params
                         method:(HMRequestMethod)method
                        success:(HMRequestSuccessBlock)success
                        failure:(HMRequestFailureBlock)failure;

#pragma mark- json request
+ (void)hm_postJsonDataWithUrl:(NSString *)url
                        params:(NSDictionary *)params
                       success:(HMRequestSuccessBlock)success
                       failure:(HMRequestFailureBlock)failure;

#pragma mark- photo request
+ (void)hm_upLoadPhotoWithUrl:(NSString *)url
                       params:(NSDictionary *)params
                    photoSize:(CGSize)photoSize
                       photos:(NSArray *)photos
                      success:(HMRequestSuccessBlock)success
                      failure:(HMRequestFailureBlock)failure;
@end

HMRequest.m
#import "HMRequest.h"

@implementation HMRequestModel


@end

@implementation HMRequest

+ (void)hm_requestActionWithUrl:(NSString *)url
                         params:(NSDictionary *)params
                         method:(HMRequestMethod)method
                        success:(HMRequestSuccessBlock)success
                        failure:(HMRequestFailureBlock)failure
{
    // [HMServerConfig HMServerAddress] 为正式/测试环境前缀可自行处理
    NSString *requestUrl = HM_FORMAT_TWO(@"%@%@", [HMServerConfig HMServerAddress], url);
    requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    if (method == HTTP_REQUEST_TYPE_GET) {
        [[HMRequest manager] GET:requestUrl
                      parameters:params
                        progress:nil
                         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                             HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
                             if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
                             if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
                         }
                         failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                             failure([HMRequest errorInfo:error]);
                         }];
    }
    if (method == HTTP_REQUEST_TYPE_POST) {
        [[HMRequest manager] POST:requestUrl
                       parameters:params progress:nil
                          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                              HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
                              if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
                              if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
                          }
                          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                              failure([HMRequest errorInfo:error]);
                          }];
    }
    if (method == HTTP_REQUEST_TYPE_PUT) {
        [[HMRequest manager] PUT:requestUrl
                      parameters:params
                         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                             HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
                             if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
                             if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
                         }
                         failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                             failure([HMRequest errorInfo:error]);
                         }];
    }
    if (method == HTTP_REQUEST_TYPE_PATCH) {
        [[HMRequest manager] PATCH:requestUrl
                        parameters:params
                           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                               HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
                               if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
                               if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
                           }
                           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                               failure([HMRequest errorInfo:error]);
                           }];
    }
    if (method == HTTP_REQUEST_TYPE_DELETE) {
        [[HMRequest manager] DELETE:requestUrl
                         parameters:params
                            success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
                                if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
                                if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
                            }
                            failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                failure([HMRequest errorInfo:error]);
                            }];
    }
}

+ (void)hm_postJsonDataWithUrl:(NSString *)url
                        params:(NSDictionary *)params
                       success:(HMRequestSuccessBlock)success
                       failure:(HMRequestFailureBlock)failure
{
    NSString *requestUrl = HM_FORMAT_TWO(@"%@%@", [HMServerConfig HMServerAddress], url);
    requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSError *error;
    NSData *jsonData     = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:requestUrl parameters:nil error:nil];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (responseObject) {
            HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
            if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
            if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
        } else {
            failure([HMRequest errorInfo:error]);
        }
    }] resume];
}

+ (void)hm_upLoadPhotoWithUrl:(NSString *)url
                       params:(NSDictionary *)params
                    photoSize:(CGSize)photoSize
                       photos:(NSArray *)photos
                      success:(HMRequestSuccessBlock)success
                      failure:(HMRequestFailureBlock)failure
{
    NSString *requestUrl = HM_FORMAT_TWO(@"%@%@", [HMServerConfig HMServerAddress], url);
    requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSLog(@"url:%@\nparams:%@", requestUrl, params);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer     = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer    = [AFJSONResponseSerializer serializer];
    [SVProgressHUD show];
    [manager POST:requestUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i < photos.count; i++) {
            NSData *imageData = UIImageJPEGRepresentation(photos[i], 0.6f);
            NSLog(@"upload image size: %ld k", (long)(imageData.length / 1024));
            NSDateFormatter *formatter = [NSDateFormatter new];
            formatter.dateFormat       = @"yyyyMMddHHmmss";
            NSString *imageName        = [formatter stringFromDate:[NSDate date]];
            NSString *fileName         = [NSString stringWithFormat:@"%@.jpg",imageName];
            [formData appendPartWithFileData:imageData name:@"image" fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
        if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
        if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
        NSLog(@"responseObject:%@", responseObject);
        [SVProgressHUD dismiss];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure([HMRequest errorInfo:error]);
    }];
}

+ (NSString *)errorInfo:(NSError *)error
{
    return error.userInfo[@"message"] ? error.userInfo[@"message"] : @"网络断开连接,请稍后再试";
}

+ (AFHTTPSessionManager *)manager
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html",
                                                            @"text/css",
                                                            @"text/json",
                                                            @"text/javascript",
                                                            @"text/plain",
                                                            @"application/json",
                                                            @"application/x-javascript",
                                                            @"application/javascript",
                                                            @"application/vnd.api+json", nil]];
    return manager;
}

@end

第二层 HMService 功能

  • 按模块进行category类别划分(例如HMNetService、HMNetService+mine)

HMService.h
#import "HMNetService.h"

@interface HMNetService (mine)

// 个人信息 -> 上传照片
+ (void)upLoadWithPhotos:(NSArray *)photos
                    type:(NSNumber *)type
                complete:(MultiActionBlock)complete;

@end
HMService.m
#import "HMNetService+mine.h"

static NSString * const upLoadImageUrl = @"/upload/image";

@implementation HMNetService (mine)

+ (void)upLoadWithPhotos:(NSArray *)photos
                    type:(NSNumber *)type
                complete:(MultiActionBlock)complete
{
    HMParams *params = [HMParams new];
    [params addParam:@"type" value:type];
    [HMRequest hm_upLoadPhotoWithUrl:upLoadImageUrl
                              params:params.params
                           photoSize:CGSizeMake(50, 50)
                              photos:photos
                             success:^(id result, HMRequestModel *model) {
                                 complete(result, model, model.message);
    } failure:^(NSString *msg) {
        complete(nil, nil, msg);
    }];
}

第三层 外部调用实现功能

  • block回调,非常简洁只关注最后结果做处理

[HMNetService upLoadWithPhotos:@[photo]
                          type:@(type)
                      complete:^(NSDictionary *result, HMRequestModel *requestModel, NSString *message) {
                 if (result) {
                    // 成功处理
                 } else {
                    // 失败处理
                 }
                 [[iToast makeText:message] show];
}];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,585评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,283评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,760评论 0 324
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,461评论 1 266
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,280评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,268评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,656评论 3 385
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,322评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,629评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,691评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,445评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,299评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,694评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,982评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,244评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,642评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,829评论 2 335

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,952评论 4 60
  • 沿着时间的堤岸 寻找水仙花和风信子 和一路的鸟叫和虫鸣...
    阆苑寒梅阅读 206评论 5 7
  • 比特是可能存在的最小的信息量,只存放1和0某一位或一连串比特所表示的意义通常是和上下文有关的每一位比特表示两种信息...
    钱塘阅读 335评论 0 0
  • 日落西山外, 我俩同时迈。 ...
    大唐青年唐英俊阅读 286评论 0 0
  • 《精进》简介----为大家提供了时间、选择、行动、学习、思维、才能、成功七个方面的精进路径,只要依循书中的方法反复...
    AlexandraW阅读 214评论 0 0