我的网络层是这么设计的

作者: findM | 来源:发表于2015-12-05 04:05 被阅读673次

1.分析

api.png

ApiPath.h 存放所有接口的路径,是一组宏定义

//域名
#define kDomain @"https://api.xxx.cn/"
//注册
#define kRegiser [NSString                stringWithFormat:@"%@login/regis",kDomain]
//登录
#define kLogin [NSString                  stringWithFormat:@"%@login/login",kDomain]
......
//以上两个接口举例子,剩下的就不多写了,没意义!

Api.h定义了项目所有的接口

#import <Foundation/Foundation.h>
#import <AFNetworking.h>//引入AFN

typedef void (^ApiSuccessBlock)(NSDictionary *dic);//请求成功的回调
typedef void (^ApiFailedBlock)(void);//请求失败的回调

@interface Api : NSObject
#pragma mark - 注册
+ (NSOperation *)apiRegisterWithPara:(NSMutableDictionary *)parameter
                             success:(ApiSuccessBlock)successBlock
                              failed:(ApiFailedBlock)failedBlock;
#pragma mark - 登陆
+ (NSOperation *)apiLogInWithPara:(NSMutableDictionary *)parameter
                         success:(ApiSuccessBlock)successBlock
                          failed:(ApiFailedBlock)failedBlock;
.....
@end

Api.m的实现部分

@implementation Api

//首先看一下发起请求的方法
/**
 *  发起请求
 *
 *  @param type         请求类型
 *  @param path         路径
 *  @param muDict       参数
 *  @param successBlock 成功回调
 *  @param failedBlock  失败回调
 *
 *  @return 请求操作的引用
 */
+(AFHTTPRequestOperation *)sendRequestWith:(NSString *)type
                                      path:(NSString *)path
                                parameters:(NSMutableDictionary *)muDict
                                   success:(ApiSuccessBlock)successBlock
                                    failed:(ApiFailedBlock)failedBlock
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //1.设置超时时间
    manager.requestSerializer.timeoutInterval = 15;
    
    //2.添加用户信息
    [self appendUserInfo:muDict];
    
    
    if ([type isEqualToString:@"get"]) {
        AFHTTPRequestOperation *request = [manager GET:path parameters:muDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
            GLLog(@"GET URL (SUCCESS) :\n%@",[operation.response.URL absoluteString]);
            GLLog(@"GET URL (RESULT)  : \n%@",responseObject);
            successBlock(responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            GLLog(@"GET URL (FAILED) :\n%@",[operation.response.URL absoluteString]);
            GLLog(@"GET URL (ERROR)  : \n%@",error);
            failedBlock();
        }];
        return request;
    }else{
        AFHTTPRequestOperation *request = [manager POST:path parameters:muDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
            GLLog(@"POST URL (SUCCESS): %@ \nPARAMETER -- \n%@",path,muDict);
            GLLog(@"POST URL (RESULT) : %@ \nRESULT -- \n%@",path,responseObject);
            
            successBlock(responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            GLLog(@"POST URL (FAILED): %@ \nPARAMETER : \n%@",path,muDict);
            GLLog(@"POST URL (FAILED): %@ \nERROR INFO:     \n%@",path,error);
            failedBlock();
        }];
        return request;
    }
}

/**
 *  追加用户信息
 *
 */
+ (void)appendUserInfo:(NSMutableDictionary *)parameter{
    
    if ([GlobalObj shareObj].account) {
        [parameter setObject:[NSString stringWithFormat:@"%d",[GlobalObj shareObj].account.user_id] forKey:@"user_id"];
        [parameter setObject:[GlobalObj shareObj].account.access_token forKey:@"access_token"];
    }
}

#pragma mark - 注册
+ (NSOperation *)apiRegisterWithPara:(NSMutableDictionary *)parameter
                             success:(ApiSuccessBlock)successBlock
                              failed:(ApiFailedBlock)failedBlock{
    return [self sendRequestWith:@"post" path:kRegiser parameters:parameter success:successBlock failed:failedBlock];
}

#pragma mark - 登陆
+ (NSOperation *)apiLogInWithPara:(NSMutableDictionary *)parameter
                         success:(ApiSuccessBlock)successBlock
                          failed:(ApiFailedBlock)failedBlock
{
    return [self sendRequestWith:@"get" path:kLoginWithMobile parameters:parameter success:successBlock failed:failedBlock];
}
//......
//后面的新的接口,在ApiPath中添加路径,在这后面添加方法就行了

@end

3.使用

以注册页面为例,在Controller中使用方法如下:

/**
 *  用来接收发起的请求,你可以把这个属性抽出来放到父类中,避免写多次
 */
@property (nonatomic, strong) NSOperation *op;
[self.parameters setObject:self.phoneField.text forKey:@"user_name"];
[self.parameters setObject:self.pwField.text forKey:@"password"];
[self.parameters setObject:self.codeField.text forKey:@"code"];
self.op = [Api apiRegisterWithPara:self.parameters success:^(NSDictionary *dic) {
   //正常
   //在这里实现Model以及刷新数据
    }
} failed:^{
    //网络错误
}];

//在Controller的dealloc方法面,取消并释放请求
//同样的,你也可以把他写在父类中去、
- (void)dealloc{
    [self.op cancel];
    self.op = nil;
}

相关文章

网友评论

  • macfai:写的真不错,学习了 :+1:
  • 0176039ba631:不好,太麻烦了,不够面向对象
    findM:@本杰明将军 更好的建议?
  • ChrisPzzz:作者可以尝试使用通知中心将网络层和controller分离
    ChrisPzzz:@laughingkid 所以需要更好的架构 通知不是首选
    laughingkid:@findM 我们现在就是用通知分离的.但是这样有一个问题,当你的网络层过重的时候,会发现很多通知在发送,搞起来很头疼.
    findM:@鹏志_Model 有道理,我试试
  • 崇德兴仁:我的也是这么封装的,但是当时没有考虑到取消请求这块,所以还的优化

本文标题:我的网络层是这么设计的

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