NSURLCache 内存缓存

来源:互联网 发布:数据质量整改报告 编辑:程序博客网 时间:2024/06/03 20:19

在 iOS 应用程序开发中,为了减少于服务端的交互次数减少网络加载频率.加快用户响应速度,一般都会在 iOS 设备中添加一个缓存机制.使用缓存的目的是为了使用的应用程序能更快速的响应用户输入,是程序高效的运行.有时候我们需要将远程 web 服务器获取的数据缓存起来,减少对同一个 url 多次请求.内存缓存我们可以使用 SDK中的NSURLCache 类.NSURLRequest 需要一个缓存参数来说明它请求的 url 如何缓存数据的.
CachePolicy 类型:
1.NSURLRequestUseProtocolCachePolicy NSURLRequest 默认的 cache policy,使用 Protocol 协议定义.
2.NSURLRequestReloadIgnoringCacheData 忽略缓存直接从原始地址下载.
3.NSURLRequestReturnCacheDataElseLoad 只有在 chche 中不存在 data 时才从原始地址下载.
4.NSURLRequestReturnCacheDataDontLoad 只使用 chche 数据,如果不存在 cache,请求失败;用于没有建立网络连接离线模式.
5.NSURLRequestReloadIgnoringLocalAndRemoteCacheData 忽略本地和远程的缓存数据,直接从原始地址下载,与NSURLRequestReloadIgnoringCacheData类似.
6.NSURLRequestReloadRevalidatingCacheData 验证本地数据与远程数据是否相同,如果不同则下载远程数据,否则使用本地数据.
NSURLCache 还提供了很多方法,来方便我们实现应用程序的缓存机制.

#import <UIKit/UIKit.h>@interface ViewController : UIViewController@property(nonatomic,strong)NSURLCache *urlCache;@property(nonatomic,strong)NSURL *url;@property(nonatomic,strong)NSMutableURLRequest *request;@property (weak, nonatomic) IBOutlet UIWebView *myWebView;@end
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    //创建 url    NSString *paramURLAsString=@"http://www.baidu.com";    self.url=[NSURL URLWithString:paramURLAsString];    //单例方法获取 cache    self.urlCache=[NSURLCache sharedURLCache];    //设置缓存空间大小    [self.urlCache setMemoryCapacity:1*1024*1024];    //创建一个请求 这个方式第一次加载的时候请求网络数据 当已经被缓存了 可以直接从缓存获取    self.request=[NSMutableURLRequest requestWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0f];    //加载网络数据    [self.myWebView loadRequest:self.request];}- (IBAction)reloadWebView:(UIButton *)sender {    //从请求中获取缓存输出    NSCachedURLResponse *response=[self.urlCache cachedResponseForRequest:self.request];    //判断是否有缓存    if (response !=nil) {        NSLog(@"如果有缓存输出,从缓存中获取数据");        //当有缓存设置 request 加载模式为不从网络加载        [self.request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];    }    //加载网络数据    [self.myWebView loadRequest:self.request];}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end
0 0
原创粉丝点击