AFNetworking 2.0并仅在离线时使用caching

当用户使用我的应用程序,他们失去了连接或使用飞行模式,我有一个问题。

我的应用服务器端不设置任何caching策略,暂时我不能改变它。 我从AFNetworking 1.x迁移到2.0,现在我在请求时使用AFHTTPRequestOperationManager 。 问题是,因为我没有在服务器端的caching策略,每个请求都是服务器(现在是好的),但如果用户无法连接到我的服务器,它不会加载caching的请求。

所以,我正在尝试以下方法,直接使用AFHTTPRequestOperation

 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告诉我没有连接,我为请求configuration了caching策略,并且它正确地从caching中加载。

问题是,这是对这种情况的正确方法吗?

你只需要AFHTTPSessionManager并检查客户端是否离线。 然后,您可以更改caching策略或强制应用程序使用caching的数据。

这里是一个非常广泛的教程如何做到这一点: http : //www.hpique.com/2014/03/how-to-cache-server-responses-in-ios-apps/