美文网首页ios知识点
关于请求工具类的封装---FRBaseHttpManage

关于请求工具类的封装---FRBaseHttpManage

作者: SnailLi | 来源:发表于2016-07-13 12:59 被阅读152次

            最近这几个月都在完成一个项目,项目里面用到了太多的数据请求,一开始还是在用以前的那种传统的请求方式,这样下来代码量就显得太多了,于是就产生了对数据请求进行一个工具类的封装,这样省事。经过这几个月的不断试验修改,现在这个工具类已经很成熟了,非常稳定了,今天给大家分享一下,废话少说了,直接上代码!

    注意:这篇文章有点长,看起来有点复杂,如果您没有做好看完这篇文章的准备,我建议您还是别再往下看了,以免影响您的心情,不过您要是坚持看到最后,肯定与惊喜!

    首先建立一个继承与NSObject的类命名为:LBRequest

    LBRequest.h 文件

    //  Created by 蜗牛 on 16/5/23.

    //  Copyright © 2016年

    /*

    关于蜗牛:一枚九零后码农

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

    个人微信:woniu1308822159

    微信公众号:woniuxueios

    简书:蜗牛学IOS  地址:http://www.jianshu.com/users/a664a9fcb096/latest_articles

    简书专题:蜗牛学IOS  地址:http://www.jianshu.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"]];

    }

    }];

    }

    到这里,基本上就把请求工具类的封装使用介绍完毕了,如果看不懂,可以联系我要源码!

    相关文章

      网友评论

        本文标题:关于请求工具类的封装---FRBaseHttpManage

        本文链接:https://www.haomeiwen.com/subject/lzbsjttx.html