URL加载系统NSURLSession 之URLCache和requestCachePolicy的使用【三】

背景:

在iOS开发中,我们需要多次的和服务器进行数据交互,为了减少与服务器的交互次数,加快app的响应速度一般的会在iOS设备中去添加一个缓存机制,减少对同一个URL的多次请求以达到更快速度的对用户的响应提高程序的运行效率

URLCache简介:

URLcache是将URL请求映射到缓存的响应对象,它提供复合的内存与磁盘缓存并允许开发者去操作内存和磁盘部分的大小以及控制持久存储的路径

一点需要注意的是,在iOS系统中如果系统磁盘不足时会清除磁盘缓存。

URLcache是线程安全的,但是请注意在对共享资源进行读取和书写时的资源竞争问题!

创建缓存实例:

1、class var shared: URLCache // 获取共享缓存实例

2、init(memoryCapacity: Int, diskCapacity: Int, diskPath: String?) // 创建新的缓存对象

例如:创建共享和自定义缓存对象

/*创建共享缓存实例*/
    func urlCacheUser() -> Void {
        let cache:URLCache = URLCache.shared
        print(cache)
    }
    
    /*创建自定义URL缓存实例*/
    func creatCustomerCache() -> Void {
        /* memoryCapacity 内存容量
         * diskCapacity 磁盘容量
         * diskPath 磁盘存储地址
         */
        let basePath:String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let cachePath = "\(basePath)/customerFile"
        let cache:URLCache = URLCache.init(memoryCapacity: 1024, diskCapacity: 1024 * 10, diskPath: cachePath)
        print(cache)
    }

缓存对象的属性

1、var currentDiskUsage: Int // 磁盘的高速缓存的当前大小

2、var diskCapacity: Int // 磁盘高速缓存大小

3、var currentMemoryUsage: Int // 内存高速缓存当前大小

4、var memoryCapacity: Int // 内存高速缓存大小

5、enum URLCache.StoragePolicy // 缓存存储策略

设置属性的代码例子,例如:

/*创建共享缓存实例*/
    func urlCacheUser() -> Void {
        let cache:URLCache = URLCache.shared
        self.setCacheConfig(cache: cache)
    }
    
    /*创建自定义URL缓存实例*/
    func creatCustomerCache() -> Void {
        /* memoryCapacity 内存容量
         * diskCapacity 磁盘容量
         * diskPath 磁盘存储地址
         */
        let basePath:String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let cachePath = "\(basePath)/customerFile"
        let cache:URLCache = URLCache.init(memoryCapacity: 1024, diskCapacity: 1024 * 10, diskPath: cachePath)
        self.setCacheConfig(cache: cache)
    }
 
    
    /*设置缓存的属性*/
    func setCacheConfig(cache:URLCache) -> Void {
        //设置磁盘高速缓存大小等
        cache.diskCapacity = 1 * 1024 * 1024
        // 设置内存高速缓存大小
        cache.memoryCapacity = 1 * 1024
    }
    

获取与存储缓存对象:

1、func cachedResponse(for: URLRequest) -> CachedURLResponse? // 返回指定URL的请求

2、func storeCachedResponse(CachedURLResponse, for: URLRequest) // 存储指定的URL请求

3、func getCachedResponse(for: URLSessionDataTask, completionHandler: (CachedURLResponse?) -> Void) // 获取task任务的URL请求

4、func storeCachedResponse(CachedURLResponse, for: URLSessionDataTask) // 存储指定task任务的URL请求
/*创建缓存*/
- (NSURLCache *)cache {
    if (!_cache) {
        _cache = NSURLCache.sharedURLCache;
        _cache.memoryCapacity = 1024 * 1024 * 1;
    }
    return _cache;
}

/*创建数据请求*/
- (NSURLRequest *)request {
    if (!_request) {
        NSURL *url = [[NSURL alloc] initWithString:@"https://www.baidu.com"];
        _request = [[NSURLRequest alloc] initWithURL:url];
    }
    return _request;
}

/*获取请求数据*/
-(void)cacheTest {
    // 获取指定的URL请求
    NSCachedURLResponse *response = [self.cache cachedResponseForRequest:self.request];
    NSData *data = response.data;
    NSLog(@"数据是:%@",data);
    
}

 

删除缓存对象:

1、func removeCachedResponse(for: URLRequest) //删除指定URL请求的缓存URL响应。

2、func removeCachedResponse(for: URLSessionDataTask) // 删除指定数据任务的缓存URL响应。

3、func removeCachedResponses(since: Date) //根据提供的日期删除缓存。

4、func removeAllCachedResponses() //删除所有存储的缓存URL响应。

综合使用例子:

提供一个按钮,点击按钮去多次执行请求方法,根据不同的方法去打印数据

#import "ViewController.h"
@interface ViewController (){
    NSURLConnection *connect;
}
@property (nonatomic,strong) NSURLRequest  *request;
@property (nonatomic,strong) UIButton  *loadButton;
@property (nonatomic,strong) NSURLCache  *cache;
@end



@implementation ViewController


- (UIButton *)loadButton {
    if (!_loadButton) {
        _loadButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 80, 80, 35)];
        [_loadButton setTitle:@"重新加载" forState:UIControlStateNormal];
        _loadButton.backgroundColor = [UIColor grayColor];
        [_loadButton addTarget:self action:@selector(loadWebView:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loadButton;
}


- (NSURLCache *)cache {
    if (!_cache) {
        _cache = NSURLCache.sharedURLCache;
        _cache.memoryCapacity = 1024 * 1024 * 1;
    }
    return _cache;
}

- (NSURLRequest *)request {
    if (!_request) {
        NSURL *url = [[NSURL alloc] initWithString:@"https://www.baidu.com"];
        _request = [[NSURLRequest alloc] initWithURL:url];
    }
    return _request;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.loadButton];
    
}

- (void)loadWebView:(UIButton *)button {
    NSCachedURLResponse *response = [self.cache cachedResponseForRequest:self.request];
    if (response != nil) {
        NSLog(@"请求已经有响应");
    } else {
         /*进行网络请求*/
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self];
        connect = connection;
    }
    /*打印数据*/
    NSData *data = [[self.cache cachedResponseForRequest:self.request] data];
    NSLog(@"%@",data);
}


/*NSURLConnection代理方法*/
- (nullable NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(nullable NSURLResponse *)respons {
    NSLog(@"NSURLResponse接受新的响应请求");
    return self.request;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"app接收到服务器发送的响应");
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"app接收到服务器发送数据");
    NSLog(@"数据大小为:%ld",data.length);
}


- (void)connection:(NSURLConnection *)connection   didSendBodyData:(NSInteger)bytesWritten
 totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
    NSLog(@"totalBytesWritten = %ld, totalBytesExpectedToWrite = %ld",totalBytesWritten, (long)totalBytesExpectedToWrite);
}

- (nullable NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
    return cachedResponse;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"请求完毕");
}

@end

 

你可能感兴趣的:(网络编程(重要),iOS,高级进阶)