基于AFN的網(wǎng)絡(luò)庫封裝

第一層 HMRequest 功能

  • HTTP 常用請(qǐng)求方式 GET POST PUT PATCH DELETE
  • POST 上傳JSON數(shù)據(jù)
  • 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] 為正式/測(cè)試環(huán)境前綴可自行處理
    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"] : @"網(wǎng)絡(luò)斷開連接,請(qǐng)稍后再試";
}

+ (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 功能

  • 按模塊進(jìn)行category類別劃分(例如HMNetService、HMNetService+mine)

HMService.h
#import "HMNetService.h"

@interface HMNetService (mine)

// 個(gè)人信息 -> 上傳照片
+ (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);
    }];
}

第三層 外部調(diào)用實(shí)現(xiàn)功能

  • block回調(diào)鸭你,非常簡(jiǎn)潔只關(guān)注最后結(jié)果做處理

[HMNetService upLoadWithPhotos:@[photo]
                          type:@(type)
                      complete:^(NSDictionary *result, HMRequestModel *requestModel, NSString *message) {
                 if (result) {
                    // 成功處理
                 } else {
                    // 失敗處理
                 }
                 [[iToast makeText:message] show];
}];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末推溃,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子缚陷,更是在濱河造成了極大的恐慌适篙,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,968評(píng)論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件箫爷,死亡現(xiàn)場(chǎng)離奇詭異嚷节,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)虎锚,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,601評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門硫痰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人窜护,你說我怎么就攤上這事效斑。” “怎么了柱徙?”我有些...
    開封第一講書人閱讀 153,220評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵缓屠,是天一觀的道長(zhǎng)奇昙。 經(jīng)常有香客問我,道長(zhǎng)敌完,這世上最難降的妖魔是什么储耐? 我笑而不...
    開封第一講書人閱讀 55,416評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮滨溉,結(jié)果婚禮上什湘,老公的妹妹穿的比我還像新娘。我一直安慰自己晦攒,他們只是感情好闽撤,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,425評(píng)論 5 374
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著勤家,像睡著了一般腹尖。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上伐脖,一...
    開封第一講書人閱讀 49,144評(píng)論 1 285
  • 那天热幔,我揣著相機(jī)與錄音,去河邊找鬼讼庇。 笑死绎巨,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的蠕啄。 我是一名探鬼主播场勤,決...
    沈念sama閱讀 38,432評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼歼跟!你這毒婦竟也來了和媳?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,088評(píng)論 0 261
  • 序言:老撾萬榮一對(duì)情侶失蹤哈街,失蹤者是張志新(化名)和其女友劉穎留瞳,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體骚秦,經(jīng)...
    沈念sama閱讀 43,586評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡她倘,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,028評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了作箍。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片硬梁。...
    茶點(diǎn)故事閱讀 38,137評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖胞得,靈堂內(nèi)的尸體忽然破棺而出荧止,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 33,783評(píng)論 4 324
  • 正文 年R本政府宣布罩息,位于F島的核電站嗤详,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏瓷炮。R本人自食惡果不足惜葱色,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,343評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望娘香。 院中可真熱鬧苍狰,春花似錦、人聲如沸烘绽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,333評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽安接。三九已至翔忽,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間盏檐,已是汗流浹背歇式。 一陣腳步聲響...
    開封第一講書人閱讀 31,559評(píng)論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留胡野,地道東北人材失。 一個(gè)月前我還...
    沈念sama閱讀 45,595評(píng)論 2 355
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像硫豆,于是被迫代替她去往敵國和親龙巨。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,901評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫熊响、插件旨别、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,029評(píng)論 4 62
  • 沿著時(shí)間的堤岸 尋找水仙花和風(fēng)信子 和一路的鳥叫和蟲鳴...
    閬苑寒梅閱讀 207評(píng)論 5 7
  • 比特是可能存在的最小的信息量,只存放1和0某一位或一連串比特所表示的意義通常是和上下文有關(guān)的每一位比特表示兩種信息...
    錢塘閱讀 339評(píng)論 0 0
  • 日落西山外, 我倆同時(shí)邁奥喻。 ...
    大唐青年唐英俊閱讀 289評(píng)論 0 0
  • 《精進(jìn)》簡(jiǎn)介----為大家提供了時(shí)間偶宫、選擇、行動(dòng)环鲤、學(xué)習(xí)纯趋、思維、才能、成功七個(gè)方面的精進(jìn)路徑吵冒,只要依循書中的方法反復(fù)...
    AlexandraW閱讀 221評(píng)論 0 0