给AFNetworking添加请求缓存功能实现在没有网络的情况下返回缓存数据
原理:先给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添加请求缓存功能实现在没有网络的情况下返回缓存数据的更多相关文章
- 微信小程序POST请求参数传递不到后台, 前台获取不到后端返回的数据, 以及 post 请求返回 404 但后台能收到数据
1 微信小程序POST请求参数传递不到后台 需要在微信请求 wx.request 改变默认 header 配置为如下 wx.request({ url: 'test.php', //仅为示例,并非真实 ...
- Okhttp设置http缓存,在没有网络的情况下加载http缓存里面的内容
HTTP_CACHE_FILENAME为缓存地址根路径: private final String HTTP_CACHE_FILENAME = "HttpCache"; priva ...
- localstorage实现带过期时间的缓存功能
前言 一般可以使用cookie,localstorage,sessionStorage来实现浏览器端的数据缓存,减少对服务器的请求. 1.cookie数据存放在本地硬盘中,只要在过期时间之前,都是有效 ...
- (转)全面认识一下.NET 4的缓存功能
很多关于.NET 4.0新特性的介绍,缓存功能的增强肯定是不会被忽略的一个重要亮点.在很多文档中都会介绍到在.NET 4.0中,缓存功能的增强主要是在扩展性方面做了改进,改变了原来只能利用内存进行缓存 ...
- iOS UIWebview添加请求头的两种方式
1.在UIWebviewDelegate的方法中拦截request,设置request的请求头,废话不多说看代码: - (BOOL)webView:(UIWebView *)webView shoul ...
- 【Java/Android性能优5】 Android ImageCache图片缓存,使用简单,支持预取,支持多种缓存算法,支持不同网络类型,扩展性强
本文转自:http://www.trinea.cn/android/android-imagecache/ 主要介绍一个支持图片自动预取.支持多种缓存算法.支持二级缓存.支持数据保存和恢复的图片缓存的 ...
- 【高并发】高并发环境下构建缓存服务需要注意哪些问题?我和阿里P9聊了很久!
写在前面 周末,跟阿里的一个朋友(去年晋升为P9了)聊了很久,聊的内容几乎全是技术,当然了,两个技术男聊得最多的话题当然就是技术了.从基础到架构,从算法到AI,无所不谈.中间又穿插着不少天马行空的想象 ...
- Volley网络框架完全解析(缓存篇)
在上一篇中讲完了Volley框架怎么使用,那么这篇就来讲讲Volley框架的缓存机制 我们看Volley内部源码发现: Volley框架内部自己处理了DiskBasedCache硬盘缓存,但是没有处理 ...
- 防抖与节流 & 若每个请求必须发送,如何平滑地获取最后一个接口返回的数据
博客地址:https://ainyi.com/79 日常浏览网页中,在进行窗口的 resize.scroll 或者重复点击某按钮发送请求,此时事件处理函数或者接口调用的频率若无限制,则会加重浏览器的负 ...
随机推荐
- H5的Video事件,控制方法,及监听
1.标签基本属性 src :视频的属性 poster:视频封面,没有播放时显示的图片preload:预加载autoplay:自动播放loop:循环播放controls:浏览器自带的控制条width:视 ...
- 译: 3. RabbitMQ Spring AMQP 之 Publish/Subscribe 发布和订阅
在第一篇教程中,我们展示了如何使用start.spring.io来利用Spring Initializr创建一个具有RabbitMQ starter dependency的项目来创建spring-am ...
- RNN,LSTM,GRU简单图解:
一篇经典的讲解RNN的,大部分网络图都来源于此:http://colah.github.io/posts/2015-08-Understanding-LSTMs/ 每一层每一时刻的输入输出:https ...
- layui表单验证
layui表单元素的校验只需在元素上加入lay-verify,layui提供了以下值. required(必填项) phone(手机号) email(邮箱) url(网址) number(数字) da ...
- Android开发(十七)——关闭中间activity
参考: http://java--hhf.iteye.com/blog/1826880
- Spring MVC学习摘要
1. context:component-scan标签的use-default-filters属性的作用以及原理分析 http://www.cnblogs.com/hafiz/p/5875770.ht ...
- Cordova开发App入门之创建android项目
Apache Cordova是一个开源的移动开发框架.允许使用标准的web技术-HTML5,CSS3和JavaScript做跨平台开发. 应用在每个平台的具体执行被封装了起来,并依靠符合标准的API绑 ...
- Nginx 1.9+PHP5.6 环境搭建
PHP5. 下载安装包 #wget http://mirrors.sohu.com/php/php-5.6.2.tar.gz #tar -zxf php- 安装php依赖的包 #yum inst ...
- Java知多少(49)throw:异常的抛出
到目前为止,你只是获取了被Java运行时系统抛出的异常.然而,程序可以用throw语句抛出明确的异常.Throw语句的通常形式如下: throw ThrowableInstance;这里,Thr ...
- LeetCode_832. Flipping an Image_Solution
原题链接 原题中文链接 一.题目描述 二.解题思路 题目所描述的意思是对每个数组先进行取反,并且对数组中的每个元素进行取反转换,所以一共要执行两个操作. 使用reverse函数解决水平翻转的操作: 由 ...