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

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

     

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

好了直接上代码了

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

+ (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

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

AFNetworking之缓存篇的更多相关文章

  1. jQuery2.x源码解析(缓存篇)

    jQuery2.x源码解析(构建篇) jQuery2.x源码解析(设计篇) jQuery2.x源码解析(回调篇) jQuery2.x源码解析(缓存篇) 缓存是jQuery中的又一核心设计,jQuery ...

  2. 缓存篇(Cache)~大话开篇

    回到占占推荐博客索引 闲话杂淡 想写这篇文章很久了,但总是感觉内功还不太够,总觉得,要写这种编程领域里的心法(内功)的文章,需要有足够的实践,需要对具体领域非常了解,才能写出来.如今,感觉自己有写这种 ...

  3. 缓存篇(Cache)~第一回 使用static静态成员实现服务器端缓存(导航面包屑)

    返回目录 今天写缓存篇的第一篇文章,在写完目录后,得到了一些朋友的关注,这给我之后的写作带来了无穷的力量,在这里,感谢那几位伙伴,哈哈! 书归正传,今天我带来一个Static静态成员的缓存,其实它也不 ...

  4. 缓存篇(Cache)~第三回 HttpModule实现网页的文件级缓存

    返回目录 再写完缓存篇第一回之后,得到了很多朋友的好评和来信,所以,决定加快步伐,尽快把剩下的文章写完,本篇是第三回,主要介绍使用HttpModule实现的文件级缓存,在看本文之前,大家需要限度Htt ...

  5. 缓存篇~第六回 Microsoft.Practices.EnterpriseLibrary.Caching实现基于方法签名的数据集缓存

    返回目录 这一讲中主要是说EnterpriseLibrary企业级架构里的caching组件,它主要实现了项目缓存功能,它支持四种持久化方式,内存,文件,数据库和自定义,对于持久化不是今天讨论的重要, ...

  6. (转)高性能网站架构之缓存篇—Redis集群搭建

    看过 高性能网站架构之缓存篇--Redis安装配置和高性能网站架构之缓存篇--Redis使用配置端口转发 这两篇文章的,相信你已经对redis有一定的了解,并能够安装上,进行简单的使用了,但是在咱们的 ...

  7. 前端技巧:禁止浏览器static files缓存篇(转)

    前端技巧:禁止浏览器static files缓存篇 由于CSS/JS文件经常需要改动,前端调试时是不希望浏览器缓存这些文件的. 本文记录博主的经验. Meta法 目前在chrome调试还没有遇到问题, ...

  8. AspnetCore 缓存篇

    AspnetCore 缓存篇 一.缓存的作用 怎样理解缓存: 其实所有的程序,架构,优化,线程...等技术手段,最终的目的都是如何使产品快速的响应用户的操作,提高用户的体验性,目标都是为了系统的使用者 ...

  9. Spring Boot 揭秘与实战(二) 数据缓存篇 - Redis Cache

    文章目录 1. Redis Cache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 Redis Cache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存 ...

随机推荐

  1. USB传输协议。——Arvin

    问题一:USB的传输线结构是如何的呢? 答案一:一条USB的传输线分别由地线.电源线.D+.D-四条线构成,D+和D-是差分输入线,它使用的是3.3V的电压(注意哦,与CMOS的5V电平不同),而电源 ...

  2. HTML5 十大新特性(六)——地理定位

    简单地用一句话概括就是,使用js获取浏览器当前所在的地理坐标,实现LBS(Location Based Service,基于定位的服务). 下面写一下它的基本调用: if(navigator.geol ...

  3. restore database

    RESTORE DATABASE CTSDW FROM DISK = '\\detego-ctsetl\Backup\CTSDW\CTSDW_backup_20160722110003_Full.ba ...

  4. 滴滴快车,安全把你带到凡科安全知识h5大赛

    滴滴出行提出"安全第一.体验第二.效率第三"的可持续发展宗旨.近期,滴滴出行还推广了"安全带"宣传,包括明星夫妻CP安全带姿势和明星后排安全带语音播报等,来提升 ...

  5. TypeError: coercing to Unicode: need string or buffer, ChatRoom found

    在用django框架中遇到一个错误,是模型编写中出的错误 TypeError: coercing to Unicode: need string or buffer, ChatRoom found 解 ...

  6. iOS时间问题

    在iOS开发中,经常会遇到各种各样的时间问题,8小时时差,时间戳,求时间间隔,农历等等.解决办法网上比比皆是,但大多零零散散,很多资料并没有说明其中问题.这里集中总结一下,以便于以后查阅和供大家参考. ...

  7. ASP.NET MVC异步上传文件

    自己做的一个小dome.贴出来分享一下: 前端: <form id="formfile" method="post" enctype="mult ...

  8. Gerald's Hexagon

    Gerald's Hexagon Gerald got a very curious hexagon for his birthday. The boy found out that all the ...

  9. Node.js的cluster模块——Web后端多进程服务

    众所周知,Node.js是单线程的,一个单独的Node.js进程无法充分利用多核.Node.js从v0.6.0开始,新增cluster模块,让Node.js开发Web服务时,很方便的做到充分利用多核机 ...

  10. JSON简介

    JSON的全称是JavaScript  Object  Notion,即JavaScript对象符号,它是一种轻量级的数据交换格式,JSON的数据格式既适合人来读/写,也适合计算机本身解析和生成.最早 ...