×

写一个带有“两级缓存”的网络请求库

96
Assuner
2017.04.20 15:08* 字数 1747

git地址:https://github.com/Assuner-Lee/GRNetRequest.git 附demo

pod 'GRNetRequest'

前言

iOS开发中, AFNetWorking已经很好的封装了网络请求,但如果把每个请求返回数据的json解析,缓存管理做到一块,请求的处理就更方便了。下面我们来看一种实现方式。

代码分析

一. json转模型

这里,我们依赖了MJExtension库,首先定义了一个类GRModel,作为其他模型类的父类。

GRModel.h
#import <UIKit/UIKit.h>

@interface GRModel : NSObject
+ (NSDictionary *)mj_replacedKeyFromPropertyName;
+ (NSDictionary *)mj_objectClassInArray;
+ (instancetype)jsonToModel:(id)json;

@end
GRModel.m
#import "GRModel.h"
#import <MJExtension/MJExtension.h>

@implementation GRModel

+ (NSDictionary *)mj_replacedKeyFromPropertyName {
    return nil;
}  ①

+ (NSDictionary *)mj_objectClassInArray {
    return nil;
}  ②

+ (instancetype)jsonToModel:(id)json {
    return [self mj_objectWithKeyValues:json];
}  ③

@end

若在一个继承GRModel的子类GRShopList中:

GRShopList.h
@interface GRShop : GRModel                             //内部类

@property (nonatomic, strong) NSString *activity;       //活动
@property (nonatomic, strong) NSString *shopType;       //店铺类型
@property (nonatomic, strong) NSString *shopDesc;       //描述
@property (nonatomic, assign) NSUInteger shopID;        //id
@property (nonatomic, strong) NSString *shopLogo;       //logo地址
@property (nonatomic, assign) NSUInteger monthSold;     //月销量
@property (nonatomic, assign) NSUInteger basePrice;     //起送价
@property (nonatomic, strong) NSString *shopName;       //商家名字
@property (nonatomic, strong) NSString *shopPhone;      //商家电话
@property (nonatomic, assign) NSUInteger rateNumber;    //评价次数
@property (nonatomic, assign) CGFloat shopRating;       //商家评分
@property (nonatomic, assign) NSUInteger shopStatus;    //店铺状态

@end


@interface GRShopList : GRModel

@property (nonatomic, assign) NSUInteger code;    
@property (nonatomic, strong) NSArray *dataArray; 
@property (nonatomic, strong) NSString *message;  

@end

GRShopList.m
@implementation GRShop

+ (NSDictionary *)mj_replacedKeyFromPropertyName {
    return @{
             @"shopType": @"category",
             @"shopDesc": @"description",
             @"shopID": @"id",
             @"shopLogo": @"logo",
             @"shopName": @"name",
             @"shopPhone": @"phone",
             @"shopRating": @"rating",
             @"shopStatus": @"status"
            };
}   ①

@end


@implementation GRShopList

+ (NSDictionary *)mj_replacedKeyFromPropertyName {
    return @{@"dataArray": @"data"};
}   ①

+ (NSDictionary *)mj_objectClassInArray {
    return @{@"dataArray": @"GRShop"};
}   ②

其中,子类通过重写方法①来映射 属性->json字符串中的键,重写方法②来映射数组名->数组中的对象类型;方法③无需重写,用来触发json转模型,在这个过程中,会执行方法①②获取映射字典。关于json如何转模型的,大致来说,是通过获取对象的属性列表,匹配属性名字及json字典中的键、属性类型及json字典键对应的值的类型,去一一赋值的。

二.请求

1.请求管理器

在AFNetworking中,AFHTTPSessionManager并没有返回单例的类方法。若每一个请求都构造一个此类的对象,不但难以统一httpHeader的管理,如token;此类对象太多还可能造成内存泄漏。

GRHTTPManager.h
#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>

typedef void (^GRRequestComplete)(id _Nullable responseObject, NSError * _Nullable error);

@interface GRHTTPManager : NSObject

+ (AFHTTPSessionManager *_Nonnull)sharedManager;
+ (void)GET:(NSString *_Nonnull)path paramsDic:(NSDictionary *_Nullable)paramsDic completionHandler:(nullable GRRequestComplete)complete;
+ (void)POST:(NSString *_Nonnull)path paramsDic:(NSDictionary *_Nullable)paramsDic completionHandler:(nullable GRRequestComplete)complete;
+ (void)PUT:(NSString *_Nonnull)path paramsDic:(NSDictionary *_Nullable)paramsDic completionHandler:(nullable GRRequestComplete)complete;

@end
GRHTTPManager.m
#import "GRHTTPManager.h"

@implementation GRHTTPManager

+ (AFHTTPSessionManager *)sharedManager {
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AFHTTPSessionManager alloc] init];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
        responseSerializer.removesKeysWithNullValues = YES;
        manager.responseSerializer = responseSerializer;
        manager.requestSerializer.timeoutInterval = 20;
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    });
    return manager;
}

#pragma mark HTTPMethod

+ (void)GET:(NSString *_Nonnull)path paramsDic:(NSDictionary *_Nullable)paramsDic completionHandler:(nullable GRRequestComplete)complete {
    [[self sharedManager] GET:path parameters:paramsDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (complete) {
            complete(responseObject, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (complete) {
            complete(nil, error);
        }
    }];
}

+ (void)POST:(NSString *_Nonnull)path paramsDic:(NSDictionary *_Nullable)paramsDic completionHandler:(nullable GRRequestComplete)complete {
    [[self sharedManager] POST:path parameters:paramsDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (complete) {
            complete(responseObject, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (complete) {
            complete(nil, error);
        }
    }];
}

+ (void)PUT:(NSString *_Nonnull)path paramsDic:(NSDictionary *_Nullable)paramsDic completionHandler:(nullable GRRequestComplete)complete {
    [[self sharedManager] PUT:path parameters:paramsDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (complete) {
            complete(responseObject, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (complete) {
            complete(nil, error);
        }
    }];
}

@end

在这里,我们创建了AFHTTPSessionManager的单例去统一管理请求、接收数据类型,httpHeader等属性。然后,我们简单封装了AFNetworking的get,post,put方法,使其写法上更简短,同时也简化了请求成功与否的判断(error是否为nil)

2.请求对象

那么,我们如何把每一个请求的配置,返回数据的解析,缓存管理及请求后的回调结合在一起呢?这里,我们定义了一个类GRNetRequestObject类,作为其他请求对象的父类。

typedef void (^GRRequestComplete)(id _Nullable responseObject, NSError * _Nullable error);
GRNetRequestObject.h
#import <Foundation/Foundation.h>
#import "GRHTTPManager.h"

typedef NS_ENUM(NSUInteger, GRHTTPMethod) {
    GRHTTPMethodGet = 1,
    GRHTTPMethodPost,
    GRHTTPMethodPut,
};         ❶

#define GRWEAK(aObject) \
__weak typeof(aObject) weak##aObject = aObject

#define GRSTRONG(aObject) \
__strong typeof(weak##aObject) aObject = weak##aObject
           ❷

@interface GRNetRequestObject : NSObject

@property (nonatomic, strong) NSString *requestPath;       ①

@property (nonatomic, assign) GRHTTPMethod httpMethod;     ②

@property (nonatomic, strong) NSString *modelClassName;    ③

@property (nonatomic, strong) id cache;                    ④

@property (nonatomic, assign) BOOL allowCache;             ⑤

- (void)startRequestComplete:(GRRequestComplete)complete;  ⑥

- (NSDictionary *)paramsDic;                               ⑦

@end

GRNetRequestObject.m
#import "GRNetRequestObject.h"
#import "GRCacheManager.h"

@interface GRNetRequestObject ()

@property (nonatomic, copy) GRRequestComplete complete;    ⑧

@end

@implementation GRNetRequestObject

- (instancetype)init {
    if (self = [super init]) {
        self.allowCache = YES;
    }
    return self;
}

- (NSDictionary *)paramsDic {
    return nil;
} ⑦

- (id)cache {
    return [GRCacheManager modelCacheOfKey:self.requestPath className:self.modelClassName];
} ④

- (void)startRequestComplete:(GRRequestComplete)complete {
    self.complete = complete;
    switch (self.httpMethod) {
        case GRHTTPMethodGet: {
            [GRHTTPManager GET:self.requestPath paramsDic:[self paramsDic] completionHandler:^(id  _Nullable responseObject, NSError * _Nullable error) {
                [self handleResponseObject:responseObject error:error];
            }];
        } break;
            
        case GRHTTPMethodPost: {
            [GRHTTPManager POST:self.requestPath paramsDic:[self paramsDic] completionHandler:^(id  _Nullable responseObject, NSError * _Nullable error) {
                [self handleResponseObject:responseObject error:error];
            }];
        } break;
            
        case GRHTTPMethodPut: {
            [GRHTTPManager PUT:self.requestPath paramsDic:[self paramsDic] completionHandler:^(id  _Nullable responseObject, NSError * _Nullable error) {
                [self handleResponseObject:responseObject error:error];
            }];
        } break;
            
        default:
            break;
    }
} ⑥

 - (void)handleResponseObject:(id)responseObject error:(NSError *)error {
1    if (!self.complete) {
2      return;
3   }
4    if (error) {
5        self.complete(nil, error);  
6        return;
7    }
8    if (responseObject) {
9        if (self.modelClassName) {
10           Class modelClass = NSClassFromString(self.modelClassName);
11           if (modelClass && [modelClass isSubclassOfClass:[GRModel class]]) {
12               GRModel *object = [modelClass jsonToModel:responseObject];
13               self.complete(object, nil);
14               if (self.allowCache && self.httpMethod == GRHTTPMethodGet) {
15                   [GRCacheManager saveCacheWithObject:object json:responseObject forKey:self.requestPath];
16               }
17            } else {
18                   [NSException raise:@"GRRequestError" format:@"class:(%@) doesn't exist or isn't subclass of GRModel", modelClass];
19            }
20       } else {
21           self.complete(responseObject, nil);
22       }
23   }
24} ⑨

@end

简单介绍下:
❶枚举定义了请求类型;
❷宏定义了一对防止Block中持有循环的代码。
①代表请求的路径;
②代表请求的类型,如get;
③代表请求成功时json数据要转换的对象的类型;
④代表请求的cache,getter方法中,以自己的请求路径和要转换的类型名字为参数去缓存管理器中查找缓存(关于自定义的缓存管理器,后讲到),缓存与请求是分开的;
⑤代表了该请求是否允许cache(限于get);
⑥代表请求开始执行的方法,参数为请求后外部对请求结果处理的代码块(可能包含视图更新等);
⑦代表请求参数的获取方法,子类应该重写该方法;
⑧代表了copy⑥中的代码块;
⑨代表了对⑧中GRHTTPManager单例执行完具体请求 结果的处理,如json转模型,缓存处理,以及把转换后的model对象,error作为⑧中参数回调给请求外部。

>>>>> ⑨ <<<<<

我们先简单看下方法⑨如何对GRHTTPManager单例执行完具体的请求结果进行处理的。
1-3:若请求没有外部回调的代码块,返回;
4-7:若GRHTTPManager单例传回的error不为空,执行外部回调代码块,返回;
下面为请求成功情况下
9-10:根据请求的modelClassName属性利用runtime里的方法尝试得到类对象;
11-13:若类对象存在且为GRModel的子类,调用GRModel的+ (instancetype)jsonToModel:(id)json;方法,返回一个GRModel对象,作为参数执行外部回调代码块;
14-16:若请求允许缓存且为get请求,将请求成功返回的json数据(数组或字典),解析后的模型对象,请求的路径作为参数,储存缓存(关于自定义的缓存管理器,后讲到)。

>>>>> ⑨ <<<<<

为了方便管理每一个请求,我们可以为每一个请求新建一个继承于GRNetRequestObject的子类。例如:

GRShopListRequest.h
#import <GRNetRequest/GRNetRequestObject.h>

@interface GRShopListRequest : GRNetRequestObject

@end
GRShopListRequest.m
#import "GRShopListRequest.h"

@implementation GRShopListRequest

- (instancetype)init {
    if (self = [super init]) {
      ①  self.requestPath = @"http://api.grooo.cn/api/v3/shops/shop?school_id=1";
      ②  self.httpMethod = GRHTTPMethodGet;
      ③  self.modelClassName = @"GRShopList";
    }
    return self;
}

@end

其中,①配置了请求路径,②配置了请求类型,③配置了请求成功时json数据要转换的对象的类型。

三. 缓存管理器

这里,我们的一种大致思路是:

存:

1 . 以请求的路径为键,值为json转换后的对象,存于NSCache中,作为“ramCache”,app退出这部分缓存消失;
2 . 以请求的路径为键,值为json数据(数组或字典),存于NSMutableDictionary中,作为romCache,并写入到磁盘的cache.plist中,app退出这部分缓存依然存在。

取:

1 . 以请求的路径为键,在缓存管理器的ramCache中寻找缓存的对象;
2 . 若1中未找到,以请求的路径为键,在缓存管理器的romCache中寻找缓存的json数据,并根据给类型转换成对象。

代码

GRCacheManager.h
@interface GRCacheManager : NSObject

+ (void)saveCacheWithObject:(GRModel *)model json:(NSDictionary *)dic forKey:(NSString *)path;

+ (id)modelCacheOfKey:(NSString *)path className:(NSString *)name;

+ (void)setCacheCountLimit:(NSUInteger)count;

+ (void)clearAllCache;

@end
GRCacheManager.m
#import "GRCacheManager.h"
#import <MJExtension/MJExtension.h>

@interface GRCacheManager ()

@property (nonatomic, strong) NSCache *ramCache;
@property (nonatomic, strong) NSMutableDictionary *romCache;
@property (nonatomic, strong) NSArray *keysArray;
@property (nonatomic, assign) NSUInteger cacheCountLimit;

@end

@implementation GRCacheManager

+ (GRCacheManager *)sharedManager {
    static GRCacheManager *maneger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        maneger = [[GRCacheManager alloc] init];
    });
    return maneger;
}

- (instancetype)init {
    if (self = [super init]) {
        self.ramCache = [[NSCache alloc] init];
        self.cacheCountLimit = 20;
        self.ramCache.countLimit = self.cacheCountLimit;
        NSMutableDictionary *romCacheDic = [NSMutableDictionary dictionaryWithContentsOfFile:[self filePath]];
        if (romCacheDic) {
            self.romCache = romCacheDic;
            self.keysArray = romCacheDic.allKeys;
        } else {
            self.romCache = [[NSMutableDictionary alloc] init];
        }
    }
    return self;
}

+ (void)saveCacheWithObject:(GRModel *)model json:(NSDictionary *)dic forKey:(NSString *)path {
    [[self sharedManager] saveCacheWithObject:model json:dic forKey:path];
}

+ (id)modelCacheOfKey:(NSString *)path className:(NSString *)modelClassName {
    return [[self sharedManager] modelCacheOfKey:path className:modelClassName];
}

+ (void)setCacheCountLimit:(NSUInteger)count {
    [self clearAllCache];
    GRCacheManager *cacheManager = [self sharedManager];
    cacheManager.cacheCountLimit = count;
    cacheManager.ramCache.countLimit = cacheManager.cacheCountLimit;
}

+ (void)clearAllCache {
    GRCacheManager *manager = [self sharedManager];
    [manager.ramCache removeAllObjects];
    [manager.romCache removeAllObjects];
    manager.keysArray = nil;
    [manager.romCache writeToFile:[manager filePath] atomically:YES];
}

#pragma - Private Methods

- (NSString *)filePath {
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"cache.plist"];
}

- (void)saveCacheWithObject:(GRModel *)model json:(NSDictionary *)dic forKey:(NSString *)path {
 @synchronized(self) {
     if (self.cacheCountLimit) {
         [self.ramCache setObject:model forKey:[path copy]];
         if (self.keysArray.count <= self.cacheCountLimit) {
             [self.romCache setObject:dic forKey:path];
         } else {
             [self.romCache removeObjectForKey:self.keysArray[0]];
             [self.romCache setObject:dic forKey:path];
         }
         self.keysArray = self.romCache.allKeys;
         [self.romCache writeToFile:[self filePath] atomically:YES];
     }
 }
}

- (id)modelCacheOfKey:(NSString *)path className:(NSString *)modelClassName {
 @synchronized(self) {
    id object = nil;
    if ([self.ramCache objectForKey:path]) {
        object = [self.ramCache objectForKey:path];
        return object;
    } else if ([self.keysArray containsObject:path]) {
        if (modelClassName) {
            Class modelClass = NSClassFromString(modelClassName);
            if (modelClass  && [modelClass isSubclassOfClass:[GRModel class]]) {
                NSDictionary *modelDic = [self.romCache objectForKey:path];
                object = [modelClass mj_objectWithKeyValues:modelDic];
                return object;
            }
        }
    }
    return object;
 }
}

@end

缓存策略

默认的缓存数量为20个,可以设置。ramCache中,cache的新老更替由NSCache自行管理; romCache中,cache的更替是达到最大缓存数量后,若再有存储缓存操作,先删掉最早的那枚缓存,在执行新的存储。

请求及缓存的使用例子

例如:

一个继承于GRNetRequestObject的请求类

GRShopListRequest.h
#import <GRNetRequest/GRNetRequestObject.h>

@interface GRShopListRequest : GRNetRequestObject

@end
GRShopListRequest.m
#import "GRShopListRequest.h"

@implementation GRShopListRequest

- (instancetype)init {
    if (self = [super init]) {
      ①  self.requestPath = @"http://api.grooo.cn/api/v3/shops/shop?school_id=1";
      ②  self.httpMethod = GRHTTPMethodGet;
      ③  self.modelClassName = @"GRShopList";
    }
    return self;
}

@end

一个继承于GRModel的模型类

如文中的GRShopList

若在某一个控制器中

- (void)initRequest {
    self.shopListRequest = [[GRShopListRequest alloc] init];
    if (self.shopListRequest.cache) {
       ① self.shopDataArray = [self.shopListRequest.cache dataArray]; 
    }
}

- (void)startRequest {
    if (!self.shopListRequest.cache) {
        [self showProgress];
    }
    GRWEAK(self);
  ②  [self.shopListRequest startRequestComplete:^(GRShopList *  _Nullable responseObject, NSError * _Nullable error) { 
        GRSTRONG(self);
        [self hideProgress];
        if (error) {
            [self showTimeOut];
            return;
        }
        [self showProgress];
        self.shopDataArray = responseObject.dataArray;
        [self hideProgress];
    }];
}

这里我们重写了shopDataArray的setter方法去驱动一个tableView的重载。
①若该请求有缓存,直接拿到缓存并重载tableView;
②直接请求,成功后重载tableView。

详情见demo

总结

我们可以看到,在请求的类中设置好路径,请求类型,json数据要转换的类型后,外部对于结果的处理是非常简便的。且每个请求的缓存与直接请求是分开的,并行的,利于管理,每一个请求用不用缓存,什么时机用缓存,完全取决于你。
同时也看到了,这个请求类error详细信息的封装是不足的,需要结合具体情况改善。

谢谢观看

水平有限,如有错误,请多指正!

git地址:https://github.com/Assuner-Lee/GRNetRequest.git 附demo

iOS开源库
Web note ad 1