關于請求工具類的封裝---FRBaseHttpManage

? ? ? ? 最近這幾個月都在完成一個項目,項目里面用到了太多的數據請求,一開始還是在用以前的那種傳統的請求方式,這樣下來代碼量就顯得太多了,于是就產生了對數據請求進行一個工具類的封裝,這樣省事。經過這幾個月的不斷試驗修改,現在這個工具類已經很成熟了,非常穩定了,今天給大家分享一下,廢話少說了,直接上代碼!

注意:這篇文章有點長,看起來有點復雜,如果您沒有做好看完這篇文章的準備,我建議您還是別再往下看了,以免影響您的心情,不過您要是堅持看到最后,肯定與驚喜!

首先建立一個繼承與NSObject的類命名為:LBRequest

LBRequest.h 文件

//? Created by 蝸牛 on 16/5/23.

//? Copyright ? 2016年

/*

關于蝸牛:一枚九零后碼農

蝸牛-----QQ:3197857495-----李富棚

個人微信:woniu1308822159

微信公眾號:woniuxueios

簡書:蝸牛學IOS? 地址:http://www.lxweimin.com/users/a664a9fcb096/latest_articles

簡書專題:蝸牛學IOS? 地址:http://www.lxweimin.com/collection/bfcf49bf5d27

*/

//. All rights reserved.

//

#import<Foundation/Foundation.h>

//導入AFNetworking頭文件

#import#import "AFNetworking.h"

@class LBResponse;

/**

* @brief 請求參數編碼

*/

typedef enum : NSUInteger{

LBRequestParameterEncodingURL = 0,

LBRequestParameterEncodingURLEncodedInURL,

LBRequestParameterEncodingJSON,

} LBRequestParameterEncoding;

/**?

*@brief接口請求

?*/

@interface LBRequest : NSObject@property (strong,nonatomic) NSString *path;

@property (strong,nonatomic) NSString *method;

@property (assign,nonatomic) LBRequestParameterEncoding encoding;@property (strong,nonatomic) NSDictionary*params;

@property (strong,nonatomic) void(^completion)(LBResponse*);

@end

/// 上傳請求

@interface LBUploadRequest : LBRequest

//文件流

@property (strong,nonatomic) NSData *fileData;

//名字

@property (strong,nonatomic) NSString *name;

//文件名字

@property (strong,nonatomic) NSString *fileName;

//文件類型

@property (strong,nonatomic) NSString *fileType;

//文件地方

@property (nonatomic , strong)NSString * fileModule;

//文件后綴

@property (nonatomic , strong)NSString * fileSuffix;

@end

/**?

*@brief請求響應?

*/

@interface LBResponse : NSObject

@property (strong,nonatomic) LBRequest *request;

@property (assign,nonatomic) NSInteger resultCode;

@property (strong,nonatomic) NSString *message;

@property (assign,nonatomic) BOOL succeed;

/**?

*? Logined表示登錄有效性,值為0表示用戶登錄狀態失效,值為1表示登錄狀態有效。?

*/

@property (assign,nonatomic) BOOL Logged;

@property (strong,nonatomic) id data;

@property (strong,nonatomic) NSDictionary*result;

@end

@interface LBService : NSObject

//檢查返回的數據

+(void)setResponseCheck:(BOOL(^)(LBResponse*))check;

+(void)pause:(LBRequest*)request;

//請求接口

+(void)request:(LBRequest*)request;

//請求接口

+(void)request:(NSString *)path method:(NSString*)method params:(NSDictionary*)params completion:(void(^)(LBResponse*))completion;

//GET請求

+(void)get:(NSString*)path params:(NSDictionary*)params completion:(void(^)(LBResponse* response))completion;

//POST請求

+(void)post:(NSString*)path params:(NSDictionary*)params completion:(void(^)(LBResponse* response))completion;

//上傳請求

+(void)upload:(NSString*)path file:(NSString*)file name:(NSString*)name fileName:(NSString*)fileName fileType:(NSString*)fileType params:(NSDictionary*)params completion:(void(^)(LBResponse* response))completion;

+(void)upload:(NSString*)path file:(NSData*)file name:(NSString*)name params:(NSDictionary*)params completion:(void(^)(LBResponse* response))completion;

//上傳頭像

+(void)uploadFileData:(UIImage *)fileData filePath:(NSString *)path fileSuffix:(NSString *)fileSuffix succeed:(void(^)(NSURLSessionTask *task, id result))succeed failed:(void(^)(NSURLSessionTask *task, NSError *error))failed;

//上傳多張圖片

+ (void)uploadIData:(NSMutableArray *)data path:(NSString*)path imageFileType:(NSString*)fileType fileModule:(NSString*)fileModule fileSuffix:(NSString *)fileSuffix succeed:(void(^)(NSURLSessionTask *task, id result))succeed failed:(void(^)(NSURLSessionTask *task, NSError *error))failed;

@end


LBService.m文件

#import "LBService.h"

@implementation LBRequest

@end

@implementation LBUploadRequest

@end

@implementation LBResponse

@end

@implementation LBService

static BOOL(^__responseCheck)(LBResponse*) = nil;

+(void)setResponseCheck:(BOOL(^)(LBResponse*))check{

__responseCheck = check;

}

+(void)response:(LBRequest*)req json:(NSDictionary*)json{

LBResponse *res = [[LBResponse alloc] init];

res.request = req;

if (json){

res.result = json;

res.message = @"請求成功";

//? ? ? ? res.message = json[@"desc"];

res.succeed=1;

if ([json isKindOfClass:[NSDictionary class]]) {

BOOL isLogined=[json[@"Logined"] intValue];

res.Logined=isLogined;

if ([[json allKeys] containsObject:@"code"]) {

int code = [json[@"code"]intValue];

if (code ==-1) {

res.succeed = 0;

}

if (!res.succeed) {

res.message=json[@"message"];

}

}

}

}else{

res.result = nil;

res.resultCode = 9999;

res.message = @"請求失??!";

res.succeed = NO;

}

if (__responseCheck) {

if (__responseCheck(res)) {

if (req.completion) {

req.completion(res);

}

}

}else{

if (req.completion) {

req.completion(res);

}

}

}

static NSMutableArray *__requestQueue;

//暫停接口的調用

+(void)pause:(LBRequest*)request{? ??

[self request:request ignorePause:YES];? ??

if (__requestQueue == nil) {? ? ? ?

?__requestQueue = [[NSMutableArray alloc] init];? ??

}

}

+(void)request:(LBRequest *)request{? ?

?[self request:request ignorePause:NO];

}

+(void)request:(LBRequest *)request ignorePause:(BOOL)ignorePause{? ?

?if (!ignorePause && __requestQueue) {? ? ? ?

?[__requestQueue addObject:request];?

?? ? ? return;? ??

}? ? static AFHTTPSessionManager *manamer;? ?

?if (manamer == nil) {? ? ? ??

manamer = [AFHTTPSessionManager manager];? ?

?}

//? ? NSString *contentType = @"text/html";

//? ? //參數編碼

// ? ?switch (request.encoding) {

//? ? ? ? case LBRequestParameterEncodingURL:

//? ? ? ? case LBRequestParameterEncodingURLEncodedInURL:

//? ? ? ? ? ? if (![manamer.requestSerializer isKindOfClass:[AFHTTPRequestSerializer class]]) {

//? ? ? ? ? ? ? ? manamer.requestSerializer = [AFHTTPRequestSerializer serializer];

//? ? ? ? ? ? ? ? contentType = @"text/html";

//? ? ? ? ? ? }

//? ? ? ? ? ? break;

//? ? ? ? case LBRequestParameterEncodingJSON:

//? ? ? ? ? ? if (![manamer.requestSerializer isKindOfClass:[AFJSONRequestSerializer class]]) {

//? ? ? ? ? ? ? ? manamer.requestSerializer = [AFJSONRequestSerializer serializer];

//? ? ? ? ? ? ? ? contentType = @"application/json";

//? ? ? ? ? ? }

//? ? ? ? ? ? break;

//? ? ? ? default:

//? ? ? ? ? ? break;

//? ? }

//? ??

//加上charset

//? ? NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

//? ? [manamer.requestSerializer setValue:[NSString stringWithFormat:@"%@; charset=%@", contentType,charset] forHTTPHeaderField:@"Content-Type"];

//? ??

//? ? AFJSONResponseSerializer *resSer = [AFJSONResponseSerializer serializer];

//? ? resSer.readingOptions = NSJSONReadingMutableContainers;

//? ? resSer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];? ? ? ? manamer.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain",nil];? ? ? ??

//? ? manamer.responseSerializer = resSer;? ??

//請求成功? ??

void(^success)(NSURLSessionDataTask *,id) = ^(NSURLSessionDataTask *task, id responseObject){? ? ? ? NSLog(@"\n收到響應:%zd\n%@\n%@",((NSHTTPURLResponse*)task.response).statusCode,request.path,responseObject);? ? ? ? [self response:request json:responseObject];? ??

};? ??

//請求失敗? ??

void(^failure)(NSURLSessionDataTask *, NSError *) = ^(NSURLSessionDataTask *task, NSError *error){? ? ? ? NSLog(@"\n收到失敗的響應:%@\n結果:%zd",error.localizedDescription,((NSHTTPURLResponse*)task.response).statusCode);? ? ? ??

[self response:request json:nil];? ?

?};? ?

?NSLog(@"\n開始請求:\nURL:\t%@\nMethod:\t%@\nParams:\t%@",request.path,request.method,request.params);? ??

if ([request isKindOfClass:[LBUploadRequest class]]) {? ? ? ??

LBUploadRequest *uploadReqeust = (LBUploadRequest*)request;? ? ? ??

[manamer POST:request.path parameters:request.params constructingBodyWithBlock:^(id_Nonnull formData) {

if (uploadReqeust.fileType) {

[formData appendPartWithFileData:uploadReqeust.fileData name:uploadReqeust.name fileName:uploadReqeust.fileName mimeType:uploadReqeust.fileType];

}else{

[formData appendPartWithFormData:uploadReqeust.fileData name:uploadReqeust.name];

}

} progress:nil success:success failure:failure];

}else{

//根據POST,GET動態調用manager下對應的方法

NSString *method = [request.method uppercaseString];

if ([method isEqualToString:@"POST"]) {

[manamer POST:request.path parameters:request.params progress:nil success:success failure:failure];

}else if([method isEqualToString:@"PUT"]){

[manamer PUT:request.path parameters:request.params success:success failure:failure];

}else if([method isEqualToString:@"DELETE"]){

[manamer DELETE:request.path parameters:request.params success:success failure:failure];

}else{

[manamer GET:request.path parameters:request.params progress:nil success:success failure:failure];

}

}

}

+(void)request:(NSString *)path method:(NSString *)method params:(NSDictionary*)params completion:(void (^)(LBResponse *))completion{? ?

?LBRequest *request = [[LBRequest alloc] init];? ?

?request.path = path;? ?

?request.method = method;? ??

request.encoding = LBRequestParameterEncodingJSON;? ?

?request.params = params;? ?

?request.completion = completion;? ?

?[self request:request];

}

+(void)get:(NSString *)path params:(NSDictionary*)params completion:(void (^)(LBResponse *))completion{? ??

LBRequest *request = [[LBRequest alloc] init];? ?

?request.path = path;? ?

?request.method = @"GET";? ?

?request.encoding = LBRequestParameterEncodingJSON;? ?

?request.params = params;? ? ? ?

?request.completion = completion;? ??

[self request:request];

}

+(void)post:(NSString *)path params:(NSDictionary*)params completion:(void (^)(LBResponse *))completion{? ?

?LBRequest *request = [[LBRequest alloc] init];? ??

request.path = path;? ?

?request.method = @"POST";? ??

request.encoding = LBRequestParameterEncodingJSON;? ?

?request.params = params;? ??

request.completion = completion;??

? [self request:request];

}

// 上傳請求

+(void)upload:(NSString*)path file:(NSString*)file name:(NSString*)name fileName:(NSString*)fileName fileType:(NSString*)fileType params:(NSDictionary*)params completion:(void(^)(LBResponse* response))completion{? ?

?LBUploadRequest *request = [[LBUploadRequest alloc] init];? ??

request.path = path;? ?

?request.fileData = file;? ??

request.name = name;? ??

request.fileName = fileName;? ??

request.fileType = fileType;? ?

?request.method = @"POST";? ??

request.encoding = LBRequestParameterEncodingJSON;? ?

?request.params = params;? ??

request.completion = completion;? ??

[self request:request];

}

+(void)upload:(NSString *)path file:(NSData *)file name:(NSString *)name params:(NSDictionary*)params completion:(void (^)(LBResponse *))completion{? ?

?LBUploadRequest *request = [[LBUploadRequest alloc] init];??

? request.path = path;? ?

?request.fileData = file;? ?

?request.name = name;? ?

?request.fileName = nil;? ?

?request.fileType = nil;? ??

request.method = @"POST";? ??

request.encoding = LBRequestParameterEncodingJSON;? ??

request.params = params;? ?

?request.completion = completion;? ??

[self request:request];

}

@end


創建FRBaseHttpManage繼承與NSObject

FRBaseHttpManage.h文件

#import<Foundation/Foundation.h>

#import#import "LBService.h"

@interface FRBaseHttpManage : NSObject

@property(nonatomic,strong)NSMutableDictionary *parameters;

@property(nonatomic,copy)NSString *requestUrl;

@end


FRBaseHttpManage.m文件

#import "FRBaseHttpManage.h"

@implementation FRBaseHttpManage

- (instancetype)init

{

self = [super init];

if (self) {

_requestUrl=@"";

_parameters=[NSMutableDictionary dictionary];

}

return self;

}

@end


到這里為止,工具類基本上建好了,下面就是如何使用了

建立FRHomeManage繼承FRBaseHttpManage

FRBaseHttpManage.h文件

#import "FRBaseHttpManage.h"

typedef enum : NSUInteger{

ISHomeTypeFocusBrand,

} ISSettingType;

@interface FRHomeManage : FRBaseHttpManage

//定義一個對外的方法

//把要傳的參數寫在方法里面

-(void)home:(ISSettingType)type PageNumber:(int)pageNumber PageSize:(int)pageSize completion:(void (^)(NSDictionary *,LBResponse *))completion;

@end


FRBaseHttpManage.m文件

#import "FRHomeManage.h"

@implementation FRHomeManage

//實現這個方法

-(void)home:(ISSettingType)type PageNumber:(int)pageNumber PageSize:(int)pageSize completion:(void (^)(NSDictionary *, LBResponse *))completion{

self.parameters=[NSMutableDictionary dictionary];

switch (type) {//判斷類型

case ISHomeTypeFocusBrand:

{//以下為要傳的參數,根據各自的需求傳參

self.requestUrl=FRURL_String(FocusBrandURL);//請求的url

if (app.user.Id) self.parameters[@"memberId"]=app.user.Id;

self.parameters[@"pageNumber"]=@(pageNumber);

self.parameters[@"pageSize"]=@(pageSize);

}

break;

default:

break;

}

//這里分了為get和post請求

[LBService get:self.requestUrl params:self.parameters completion:^(LBResponse *response){

if (response.succeed) {

switch (type) {

case ISHomeTypeFocusBrand:

{

NSLog(@"關注品牌:%@",response.result);//請求成功了打印數據

completion(response.result,response);

}

break;

default:

break;

}

}else completion(nil,response);

}];

}


在控制器里實現這個方法

-(void)requestFocusData{

WEAKSELF;

[weakSelf addHUD:@"正在加載數據..."];

FRHomeManage *manage=[[FRHomeManage alloc]init];

[manage home:ISHomeTypeFocusBrand PageNumber:1 PageSize:100 completion:^(NSDictionary *array, LBResponse *response){

[weakSelf.HUD hide:YES];

if (response.succeed) {//判斷是否請求成功,返回的是json類型

_focusArray=[array objectForKey:@"data"];

[_collectionView reloadData];

[weakSelf addHUD:[array objectForKey:@"message"]];

}else{

[weakSelf addHUD:[array objectForKey:@"message"]];

}

}];

}

到這里,基本上就把請求工具類的封裝使用介紹完畢了,如果看不懂,可以聯系我要源碼!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,316評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,481評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 176,241評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,939評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,697評論 6 409
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,182評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,247評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,406評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,933評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,772評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,973評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,516評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,209評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,638評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,866評論 1 285
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,644評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,953評論 2 373

推薦閱讀更多精彩內容