原理:先给NSURLSession地Configuration设置一个内存和本地代理,原来的网络请求结束后会查找缓存的代理字典,并执行代理对象对应的操作方法,需要做的就是拦截错误的方法,返回缓存的数据

AFURLSessionManager.m

- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
self = [super init];
if (!self) {
return nil;
} if (!configuration) {
configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
} self.sessionConfiguration = configuration; #pragma mark 在这里给网络加上一个缓存
[self addURLCacheForRequestSession:configuration]; self.operationQueue = [[NSOperationQueue alloc] init];
self.operationQueue.maxConcurrentOperationCount = ; self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue]; self.responseSerializer = [AFJSONResponseSerializer serializer]; self.securityPolicy = [AFSecurityPolicy defaultPolicy]; #if !TARGET_OS_WATCH
self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
#endif self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init]; self.lock = [[NSLock alloc] init];
self.lock.name = AFURLSessionManagerLockName; [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
for (NSURLSessionDataTask *task in dataTasks) {
[self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil];
} for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
[self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil];
} for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
[self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil];
}
}]; return self;
} #pragma mark 添加缓存
-(void)addURLCacheForRequestSession:(NSURLSessionConfiguration*)configuration
{
if ([[[UIDevice currentDevice] systemVersion] compare:@"8.2" options:NSNumericSearch] == NSOrderedAscending) {
configuration.URLCache = [NSURLCache sharedURLCache];
}
else {
configuration.URLCache = [[NSURLCache alloc] initWithMemoryCapacity: * *
diskCapacity: * *
diskPath:@"customer_request_cache"];
}
}

AFURLSessionManagerTaskDelegate  实现方法添加部分代码

#pragma mark - NSURLSessionTaskDelegate

- (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
__strong AFURLSessionManager *manager = self.manager; __block id responseObject = nil; __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer; //Performance Improvement from #2672
NSData *data = nil;
if (self.mutableData) {
data = [self.mutableData copy];
//We no longer need the reference, so nil it out to gain back some memory.
self.mutableData = nil;
} if (self.downloadFileURL) {
userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
} else if (data) {
userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
} if (error) {
#pragma mark 网络错误时读取网络缓存数据
if (error.code == -) {
NSURLCache *cache = self.manager.session.configuration.URLCache;
if (cache) {
NSCachedURLResponse *response = [cache cachedResponseForRequest:task.currentRequest];
dispatch_async(url_session_manager_processing_queue(), ^{
NSError *serializationError = nil;
responseObject = [manager.responseSerializer responseObjectForResponse:response.response data:response.data error:&serializationError]; if (self.downloadFileURL) {
responseObject = self.downloadFileURL;
} if (responseObject) {
userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
} if (serializationError) {
userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
} dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(response.response, responseObject, serializationError);
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
});
}
}
else {
userInfo[AFNetworkingTaskDidCompleteErrorKey] = error; dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, error);
} dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
} } else {
dispatch_async(url_session_manager_processing_queue(), ^{
NSError *serializationError = nil;
responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError]; if (self.downloadFileURL) {
responseObject = self.downloadFileURL;
} if (responseObject) {
userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
} if (serializationError) {
userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
} dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, serializationError);
} dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
});
}
}
//网络请求错误代码
enum {
NSURLErrorUnknown = -,
NSURLErrorCancelled = -,
NSURLErrorBadURL = -,
NSURLErrorTimedOut = -,
NSURLErrorUnsupportedURL = -,
NSURLErrorCannotFindHost = -,
NSURLErrorCannotConnectToHost = -,
NSURLErrorDataLengthExceedsMaximum = -,
NSURLErrorNetworkConnectionLost = -,
NSURLErrorDNSLookupFailed = -,
NSURLErrorHTTPTooManyRedirects = -,
NSURLErrorResourceUnavailable = -,
NSURLErrorNotConnectedToInternet = -,
NSURLErrorRedirectToNonExistentLocation = -,
NSURLErrorBadServerResponse = -,
NSURLErrorUserCancelledAuthentication = -,
NSURLErrorUserAuthenticationRequired = -,
NSURLErrorZeroByteResource = -,
NSURLErrorCannotDecodeRawData = -,
NSURLErrorCannotDecodeContentData = -,
NSURLErrorCannotParseResponse = -,
NSURLErrorInternationalRoamingOff = -,
NSURLErrorCallIsActive = -,
NSURLErrorDataNotAllowed = -,
NSURLErrorRequestBodyStreamExhausted = -,
NSURLErrorFileDoesNotExist = -,
NSURLErrorFileIsDirectory = -,
NSURLErrorNoPermissionsToReadFile = -,
NSURLErrorSecureConnectionFailed = -,
NSURLErrorServerCertificateHasBadDate = -,
NSURLErrorServerCertificateUntrusted = -,
NSURLErrorServerCertificateHasUnknownRoot = -,
NSURLErrorServerCertificateNotYetValid = -,
NSURLErrorClientCertificateRejected = -,
NSURLErrorClientCertificateRequired = -,
NSURLErrorCannotLoadFromNetwork = -,
NSURLErrorCannotCreateFile = -,
NSURLErrorCannotOpenFile = -,
NSURLErrorCannotCloseFile = -,
NSURLErrorCannotWriteToFile = -,
NSURLErrorCannotRemoveFile = -,
NSURLErrorCannotMoveFile = -,
NSURLErrorDownloadDecodingFailedMidStream = -,
NSURLErrorDownloadDecodingFailedToComplete = -
}

给AFNetworking添加请求缓存功能实现在没有网络的情况下返回缓存数据的更多相关文章

  1. 微信小程序POST请求参数传递不到后台, 前台获取不到后端返回的数据, 以及 post 请求返回 404 但后台能收到数据

    1 微信小程序POST请求参数传递不到后台 需要在微信请求 wx.request 改变默认 header 配置为如下 wx.request({ url: 'test.php', //仅为示例,并非真实 ...

  2. Okhttp设置http缓存,在没有网络的情况下加载http缓存里面的内容

    HTTP_CACHE_FILENAME为缓存地址根路径: private final String HTTP_CACHE_FILENAME = "HttpCache"; priva ...

  3. localstorage实现带过期时间的缓存功能

    前言 一般可以使用cookie,localstorage,sessionStorage来实现浏览器端的数据缓存,减少对服务器的请求. 1.cookie数据存放在本地硬盘中,只要在过期时间之前,都是有效 ...

  4. (转)全面认识一下.NET 4的缓存功能

    很多关于.NET 4.0新特性的介绍,缓存功能的增强肯定是不会被忽略的一个重要亮点.在很多文档中都会介绍到在.NET 4.0中,缓存功能的增强主要是在扩展性方面做了改进,改变了原来只能利用内存进行缓存 ...

  5. iOS UIWebview添加请求头的两种方式

    1.在UIWebviewDelegate的方法中拦截request,设置request的请求头,废话不多说看代码: - (BOOL)webView:(UIWebView *)webView shoul ...

  6. 【Java/Android性能优5】 Android ImageCache图片缓存,使用简单,支持预取,支持多种缓存算法,支持不同网络类型,扩展性强

    本文转自:http://www.trinea.cn/android/android-imagecache/ 主要介绍一个支持图片自动预取.支持多种缓存算法.支持二级缓存.支持数据保存和恢复的图片缓存的 ...

  7. 【高并发】高并发环境下构建缓存服务需要注意哪些问题?我和阿里P9聊了很久!

    写在前面 周末,跟阿里的一个朋友(去年晋升为P9了)聊了很久,聊的内容几乎全是技术,当然了,两个技术男聊得最多的话题当然就是技术了.从基础到架构,从算法到AI,无所不谈.中间又穿插着不少天马行空的想象 ...

  8. Volley网络框架完全解析(缓存篇)

    在上一篇中讲完了Volley框架怎么使用,那么这篇就来讲讲Volley框架的缓存机制 我们看Volley内部源码发现: Volley框架内部自己处理了DiskBasedCache硬盘缓存,但是没有处理 ...

  9. 防抖与节流 & 若每个请求必须发送,如何平滑地获取最后一个接口返回的数据

    博客地址:https://ainyi.com/79 日常浏览网页中,在进行窗口的 resize.scroll 或者重复点击某按钮发送请求,此时事件处理函数或者接口调用的频率若无限制,则会加重浏览器的负 ...

随机推荐

  1. Windows 不能复制文件到远程服务器的解决办法

    1.  开始 -> 运行->浏览->C:\Windows\System32\rdpclip.exe->打开. 2. 打开资源管理器的进程可以看到 rdp复制粘贴正在运行,即可.

  2. 游戏编程精粹学习 - 使用Bloom过滤来提高计算性能(BloomFilter)

    原文在<游戏编程精粹2>的1.2中,BloomFilter是一种可以快速检测是否存在集合包含关系的数据结构,但有一定的误识别率. 该结构的优点 判断包含关系时效率较高,粗略测试了下比Lis ...

  3. 【ARM】arm系列知识框架

    [ARM编程模型] 硬件: 电路原理图 软件: 体系结构, 指令集, 寄存器组 [ARM编程技术] 汇编/C语言 编译, 链接, 烧写和调试 windows: MDK linux  : gcc [AR ...

  4. SDL获得屏幕属性及实现分析

    [时间:2017-05] [状态:Open] [关键词:sdl2,屏幕分辨率,显示区域,多媒体渲染,窗口,sdl2源码分析] 0 引言 本文的主要目标在于使用SDL2获得屏幕相关的属性,比如分辨率.屏 ...

  5. C++ 成员函数赋值给C 的函数指针的采坑录

    最近做一个banana Pi M1+的硬解码器封装成类的时候,由于是依赖ffmpeg的,而ffmpeg是C 实现的,本来demo 都是直接用C写的,测试也没有问题,想着封装也不会有问题,至少自己对C+ ...

  6. (原)关于获取ffmpeg解析rtsp流sdp中带有sps,pps的情况

     转载请注明出处:http://www.cnblogs.com/lihaiping/p/6612511.html 今天同事准备在android下使用ffmpeg来获取rtsp流,问我如何获取获取sps ...

  7. 避免在构造函数中调用虚方法(Do not call overridable methods in constructors)

    CLR中说道,不要在构造函数中调用虚方法,原因是假如被实例化的类型重写了虚方法,就会执行派生类型对虚方法的实现.但在这个时候,尚未完成对继承层次结构中所有字段的初始化.所以,调用虚方法会导致不可预测的 ...

  8. Oracle 11g:bin目录下3个特效权限的文件:root用户所有者 + s权限

  9. rtmp简要流程

  10. mysql5.5 报Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

    通过yum 的webstatic源安装的mysql55w-server,然后用service mysqld start启动时报 MySQL Daemon failed to start.Startin ...