玩转iOS开发 - 数据缓存

Why Cache

有时候。对同一个URL请求多次,返回的数据可能都是一样的,比方server上的某张图片。不管下载多少次,返回的数据都是一样的。

这里写图片描写叙述

上面的情况会造成下面问题

(1)用户流量的浪费
(2)程序响应速度不够快

解决上面的问题。一般考虑对数据进行缓存。

数据缓存

为了提高程序的响应速度,能够考虑使用缓存(内存缓存\硬盘缓存)r

这里写图片描写叙述

第一次请求数据时,内存缓存中没有数据。硬盘缓存中没有数据。

缓存数据的过程:

这里写图片描写叙述

• 当server返回数据时,须要做下面步骤
(1)使用server的数据(比方解析、显示)
(2)将server的数据缓存到硬盘(沙盒)
 此时缓存的情况是:内存缓存中有数据,硬盘缓存中有数据。

• 再次请求数据分为两种情况:
(1)假设程序并没有被关闭,一直在执行
      请求数据-> 内存数据
(2)假设程序又一次启动
    请求数据->硬盘数据-> 再次请求数据-> 内存数据

提示:数据从硬盘读入内存-> 程序开启-> 内存中一直有数据

缓存的实现

说明:

• 因为GET请求一般用来查询数据
• POST请求通常是发大量数据给server处理(变动性比較大)
=>因此一般仅仅对GET请求进行缓存,而不正确POST请求进行缓存

• 在iOS中。能够使用NSURLCache类缓存数据
• iOS 5之前:仅仅支持内存缓存。

从iOS 5開始:同一时候支持内存缓存和硬盘缓存

NSURLCache

iOS中得缓存技术用到了NSURLCache类。
• 缓存原理:一个NSURLRequest相应一个NSCachedURLResponse
• 缓存技术:把缓存的数据都保存到数据库中。

NSURLCache的常见使用方法

(1)获得全局缓存对象(不是必需手动创建)

    NSURLCache *cache = [NSURLCache sharedURLCache]; 

(2)设置内存缓存的最大容量(字节为单位,默觉得512KB)

    - (void)setMemoryCapacity:(NSUInteger)memoryCapacity;

(3)设置硬盘缓存的最大容量(字节为单位,默觉得10M)

- (void)setDiskCapacity:(NSUInteger)diskCapacity;

(4)硬盘缓存的位置:

    沙盒/Library/Caches

(5)取得某个请求的缓存

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request; 

(6)清除某个请求的缓存

    - (void)removeCachedResponseForRequest:(NSURLRequest *)request;

(7)清除全部的缓存

- (void)removeAllCachedResponses;

缓存GET请求

要想对某个GET请求进行数据缓存。很easy
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

// 设置缓存策略
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;

仅仅要设置了缓存策略,系统会自己主动利用NSURLCache进行数据缓存

7种缓存策略

• NSURLRequestUseProtocolCachePolicy // 默认的缓存策略(取决于协议)

• NSURLRequestReloadIgnoringLocalCacheData // 忽略缓存。又一次请求

• NSURLRequestReturnCacheDataElseLoad// 有缓存就用缓存。没有缓存就又一次请求  

• NSURLRequestReturnCacheDataDontLoad// 有缓存就用缓存,没有缓存就不发请求。当做请求出错处理(用于离线模式)

NSURLRequestReloadIgnoringLocalAndRemoteCacheData // 未实现
NSURLRequestReloadRevalidatingCacheData // 未实现
NSURLRequestReloadIgnoringLocalAndRemoteCacheData // 未实现

缓存的注意事项

缓存的设置须要根据详细的情况考虑,假设请求某个URL的返回数据:

    (1)常常更新:不能用缓存!

比方股票、彩票数据 (2)一成不变:果断用缓存 (3)偶尔更新:能够定期更改缓存策略 或者 清除缓存

提示:假设大量使用缓存。会越积越大,建议定期清除缓存

GET缓存

  • 在appDelegate中设置网络缓存大小
  • 实现get 缓存:
    • 假设从server载入数据,通过etag 推断载入数据与缓存是否同样
    • 从本地载入数据
    //
    //  AppDelegate.m
    //  A-get缓存请求
    //
    //  Created by Mr.Sunday on 15/4/27.
    //  Copyright (c) 2015年 Novogene. All rights reserved.
    //

    #import "AppDelegate.h"

    @interface AppDelegate ()

    @end

    @implementation AppDelegate
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    {

        /*===============设置网络缓存==============*/
        /**
         内存缓存->4M
         磁盘缓存->20M
         diskPath 假设是 nil,会缓存到 cached 的 bundleId 目录下

         仅仅要在 AppDelegate 中添加下面两句话,今后全部的缓存处理,就不须要管了!
         */

        NSURLCache *cathe = [[NSURLCache alloc] initWithMemoryCapacity:4*1024*1024 diskCapacity:20*1024*1024 diskPath:nil];
        [NSURLCache setSharedURLCache:cathe];

        /**
         SDWebImage 的缓存
         1. 缓存时间:1周
         2. 处理缓存文件。监听系统退出到后台的事件
         - 遍历缓存目录。删除全部过期的文件
         - 继续遍历缓存目录,将最大的文件删除。一直删除到缓存文件的大小和指定的“磁盘限额”一致。停止
         */
        return YES;
    }
    //
    //  ViewController.m
    //  A-get缓存请求
    //
    //  Created by Mr.Sunday on 15/4/27.
    //  Copyright (c) 2015年 Novogene. All rights reserved.
    //

    #import "ViewController.h"

    @interface ViewController ()

    @property (nonatomic, weak) IBOutlet UIImageView *iconView;
    //server返回的etag
    @property (nonatomic, copy) NSString *etag;
    //清楚全部缓存
    - (void)removeAllCachedResponses;

    @end

    @implementation ViewController

    - (void)viewDidLoad 
    {
        [super viewDidLoad];
    }

    /**
     1. 请求的缓存策略使用 >NSURLRequestReloadIgnoringCacheData<,忽略本地缓存
     2. server响应结束后。要记录 Etag,server内容和本地缓存对照是否变化的重要根据!

3. 在发送请求时。设置 If-None-Match,而且传入 etag 4. 连接结束后,要推断响应头的状态码。假设是 304,说明本地缓存内容没有发生变化 */ /*==================从本地缓存载入数据==============*/ /* NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request]; self.iconView.image = [UIImage imageWithData:cachedResponse.data]; */ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSURL *url = [NSURL URLWithString:@"http://mrsunday.local/ml.png"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0]; /** *设置请求头->全部的请求头都是通过这样的方法设置的 *假设etag length不为0,说明已经有缓存了 */ if (self.etag.length > 0) { NSLog(@"设置 etag: %@", self.etag); [request setValue:self.etag forHTTPHeaderField:@"IF-None-Match"]; } //请求的默认方法是get(高频使用) NSLog(@"%@",request.HTTPMethod); /** *Etag = "\"4a0b9-514a2d804bd40\""; *能够在请求中添加一个 etag 跟server返回的 etag 进行对照 *就能够推断server相应的资源是否发生变化,详细更新的时间,由request自行处理 */ [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; /** *allHeaderFields 全部相应头子端 */ NSLog(@"%@ %@", httpResponse.allHeaderFields, httpResponse); /** *假设server的状态码是304。说明数据已经被缓存,server不再须要返回数据 *须要从本地缓存获取被缓存的数据 */ if (httpResponse.statusCode == 304) { NSLog(@"load local database"); /** *针对http訪问的一个缓存类,提供了一个单例 *拿到被缓存的响应 */ NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request]; self.iconView.image = [UIImage imageWithData:cachedResponse.data]; return; } //记录etag self.etag = httpResponse.allHeaderFields[@"etag"]; self.iconView.image = [UIImage imageWithData:data]; }]; } //记得要清除缓存请求!

- (void)removeAllCachedResponses { [self removeAllCachedResponses]; } @end

posted @ 2016-03-27 08:02  phlsheji  阅读(591)  评论(0编辑  收藏  举报