ASIHTTPRequest缓存计策的设置
ASIHTTPRequest缓存策略的设置
ASIHTTPRequest 是一款强大的网络请求框架,该框架自带了数据的缓存策略,下面来介绍该功能的使用方法。
1.创建缓存对象
//创建缓存对象 ASIDownloadCache *asiCache = [[ASIDownloadCache alloc] init]; //设置缓存目录,这里设置沙盒目录下的Documents目录作为缓存目录 NSString *document = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; [asiCache setStoragePath:document]; //设置缓存策略 [asiCache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
2.请求对象设置缓存
//创建数据请求对象 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlstring]]; /* *设置缓存策略 *ASICacheForSessionDurationCacheStoragePolicy 程序下次启动会清除本地的缓存数据 *ASICachePermanentlyCacheStoragePolicy 是持久缓存,程序下次启动,缓存仍然还在 */ request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy; [request setDownloadCache:[UserContext shareInstance].cache]; //开始异步请求网络 [request startAsynchronous];
3.数据请求完成后
//网络数据加载完成后调用的block [request setCompletionBlock:^{ NSString *responseString = request.responseString; //打印返回的数据 NSLog(@"%@",responseString); //判断返回的数据是否来自本地缓存 if (request.didUseCachedResponse) { NSLog(@"使用缓存数据"); } else { NSLog(@"请求网络数据"); } }];