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

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

     

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

好了直接上代码了

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

+ (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. EasyUI的combobox控件使用onchange 问题

    在项目中几次都遇到了同样的问题,现在都不知道怎样解决了! 路过的朋友们帮我看看嘛!谢谢了! 最后我想要实现的效果是这样的.   在下拉列表中不存在值.(这里的是下拉列表中存在值的!)  但是在我输入值 ...

  2. Failed deleting my ephemeral node

    2017-01-05 11:07:39,490 WARN zookeeper.RecoverableZooKeeper: Node /hyperbase1/rs/tw-node1217,60020,1 ...

  3. JavaScript获取浏览器类型与版本

    从网上找到一段使用JavaScript判断浏览器以及浏览器版本的比较好的代码,在此记录一下: <script type="text/javascript"> var S ...

  4. js判断中文

    var reg = /^[\u4E00-\u9FA5]+$/;if(!reg.test(keywordscn)){ alert('请填写中文') return false;}

  5. svn 版本控制

    首先来下载和搭建SVN服务器. Subversion已经迁移到apache网站上了,下载地址: http://subversion.apache.org/packages.html windows操作 ...

  6. Python anaconda links to GOMP_4.0 and throws error

    ImportError: /usr/progtools/anaconda2/bin/../lib/libgomp.so.1: version `GOMP_4.0' not found (require ...

  7. linux shell技巧

    一.在SHELL编程中,经常要处理一些字符串变量.比如,计算长度啊.截取子串啊.字符替换啊等等,常常要用到awk.expr.sed.tr等命令.下面给大家介绍个简单的字符串处理方法,用不着嵌套复杂的子 ...

  8. Stack与Queue

    一.Stack的方法 1. public void push(int node)  把项 压入栈顶.其作用与 addElement (node) 相同.   不一定是int,可以是节点 stack.p ...

  9. Javascript理解this对象

    this是函数运行时自动生成的一个内部对象,只能在函数内部使用,但总指向调用它的对象. 通过以下几个例子加深对this的理解. (1)作为函数调用 var name = 'Jenny'; functi ...

  10. python【0】-目录

    python[1]-基础知识 Python[2]-列表和元组 Python[3]-字典dic和集合set python[4]-函数 python[5]-生成式,生成器 python[6]-函数式编程 ...