AFNetworking之缓存篇

苦苦看了我两天,最近后台为了减轻压力,要我做缓存,我说好吧......

借鉴了别人的说法找到一张图可以看明白好多:


     

这个是我比较战成一种方案。

好了直接上代码了

首先我们要有自己缓存的类 说以就自己用读写方式简单写了一个类

+ (void)cacheForData:(NSData *)data fileName:(NSString *)fileName

{

NSString *path = [kCachePath stringByAppendingPathComponent:[YBMD5 md5:fileName]];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

[data writeToFile:path atomically:YES];

});

}

+ (NSData *)getCacheFileName:(NSString *)fileName

{

NSString *path = [kCachePath stringByAppendingPathComponent:[YBMD5 md5:fileName]];

return [[NSData alloc] initWithContentsOfFile:path];

}

+ (NSUInteger)getAFNSize

{

NSUInteger size = 0;

NSFileManager *fm = [NSFileManager defaultManager];

NSDirectoryEnumerator *fileEnumerator = [fm enumeratorAtPath:kCachePath];

for (NSString *fileName in fileEnumerator) {

NSString *filePath = [kCachePath stringByAppendingPathComponent:fileName];

NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];

size += [attrs fileSize];

}

return size;

}

这些大家都有自己的方式  。

然后开始在我们的AF中写一些东西 就可以了

-(AFHTTPSessionManager *)manager{

static AFHTTPSessionManager *rmanager = nil;

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

rmanager = [AFHTTPSessionManager manager];

rmanager.responseSerializer = [AFJSONResponseSerializer serializer];

rmanager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"image/jpg",@"application/x-javascript",@"keep-alive", nil];

// 设置超时时间

[rmanager.requestSerializer willChangeValueForKey:@"timeoutInterval"];

rmanager.requestSerializer.timeoutInterval = 60.f;

[rmanager.requestSerializer didChangeValueForKey:@"timeoutInterval"];

});

return rmanager;

}

-(void)requsetWithPath:(NSString *)path withParams:(NSDictionary *)params withCacheType:(YBCacheType)cacheType withRequestType:(NetworkRequestType)type withResult:(ZmzBlock)resultBlock{

if (!self.isConnected) {

NSLog(@"没有网络,建议在手机设置中打开网络");

//  return;

}

switch (type) {

case NetworkGetType:

{

YBCache *cache = [self getCache:cacheType url:path params:params withResult:resultBlock];

NSString *fileName = cache.fileName;

if (cache.result) return;

[self.manager GET:path parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {

YBLog(@"---------%lld", downloadProgress.totalUnitCount);

} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

if (resultBlock) {

//缓存数据

NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];

[YBCacheTool cacheForData:data fileName:fileName];

[self handleRequestResultWithDataTask:task responseObject:responseObject error:nil resultBlock:resultBlock];

}

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

[self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];

}];

}

break;

case NetworkPostType:

{

NSString *cutPath = [NSString stringWithFormat:@"%@%@",MAIN_URLL,path];

//缓存数据的文件名 data

YBCache *cache = [self getCache:cacheType url:cutPath params:params withResult:resultBlock];

NSString *fileName = cache.fileName;

if (cache.result) return;

[self.manager POST:cutPath parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {

} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

if (resultBlock) {

//缓存数据

NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];

[YBCacheTool cacheForData:data fileName:fileName];

[self handleRequestResultWithDataTask:task responseObject:responseObject error:nil resultBlock:resultBlock];

}

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

[self handleRequestResultWithDataTask:task responseObject:nil error:error resultBlock:resultBlock];

}];

}

break;

default:

break;

}

}

这样大致的步骤就搞定了,可以根据自己的项目需求来定。

这只是成功的第一步 之后又整了半天 整理到了git上去

https://github.com/walkingzmz/MZAFNetworking

有兴趣的可以一起讨论下。

原文地址:https://www.cnblogs.com/walkingzmz/p/6051377.html