AFNetworking 2.0并仅在离线时使用缓存 [英] AFNetworking 2.0 and use cache only when offline
问题描述
当用户使用我的应用并且他们失去连接或使用飞行模式时,我遇到了问题。
I have a problem when users use my app and they lost connection or use airplane mode.
我的应用服务器端没有设置任何缓存策略我无法改变它。我从AFNetworking 1.x迁移到2.0,现在我在发出请求时使用 AFHTTPRequestOperationManager
。问题是因为我在服务器端没有缓存策略,所以每个请求都发送到服务器(现在可以正常)但是如果用户无法连接到我的服务器,它就不会加载缓存的请求。
My app server side doesn't set any cache policy and for the time being I can't change it. I migrated from AFNetworking 1.x to 2.0 and now I'm using AFHTTPRequestOperationManager
when making requests. The problem is that because I have no cache policy on the server side, every request is made to the server (which for now is fine) but if the user is not able to connect to my server, it doesn't load the cached request.
所以,我正在尝试以下方法,直接使用 AFHTTPRequestOperation
:
So, I'm trying the following, using AFHTTPRequestOperation
directly like this:
NSURL *URL = [NSURL URLWithString:filePath];
NSMutableURLRequest *request = [[NSURLRequest requestWithURL:URL] mutableCopy];
if (![[AFNetworkReachabilityManager sharedManager] isReachable]) {
[request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
}
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[[NSOperationQueue mainQueue] addOperation:op];
这样,如果 AFNetworkReachabilityManager
告诉我那里有没有连接,我为请求配置了缓存策略,并且它是从缓存中正确加载的。
This way, if AFNetworkReachabilityManager
tells me there's no connectivity, I configured the cache policy for the request and it is loaded from the cache correctly.
问题是,这是解决这种情况的正确方法吗?
The question is, is this the right approach to this situation?
推荐答案
你只需要继承 AFHTTPSessionManager
并检查客户端是否离线。然后,您可以更改缓存策略或强制应用程序使用缓存数据。
You just need to subclass the AFHTTPSessionManager
and check if the client is offline. Then you can change the cache policy or force the app to use cached data.
这是一个非常广泛的教程,如何执行此操作: http://www.hpique.com/2014/03/how- to-cache-server-responses-in-ios-apps /
Here is a very extensive tutorial how to do this: http://www.hpique.com/2014/03/how-to-cache-server-responses-in-ios-apps/
这篇关于AFNetworking 2.0并仅在离线时使用缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!