zoukankan      html  css  js  c++  java
  • iOS NSURLCache

    1.如果向同一个URL请求多次,返回的数据是一样的,可以考虑用缓存,以提高响应速度,节省用户流量

    2.缓存的思路

    客户端发起请求之前,检测内存缓存: a.内存缓存有数据,则使用内存缓存的数据

                      b.内存缓存没数据,则监测硬盘(沙盒)缓存: c.硬盘缓存有数据,则使用硬盘缓存

                                             d.硬盘缓存没数据,则向服务器发请求获取数据

    3.缓存数据的过程

    4.缓存的实现,一般是GET请求需要做数据缓存,POST请求不需要.

    苹果提供NSURLCache类专门处理数据缓存

    5.NSURLCache的用法

    5.1苹果提供了一个全局的缓存对象,用于管理缓存

      NSURLCache *cache = [NSURLCache sharedURLCache];

        [cache setMemoryCapacity:1024 * 1024];  // 设置内存缓存容量=1M;如果不设置,默认=512KB

        [cache setDiskCapacity:20 * 1024 * 1024]; // 设置硬盘缓存容量=20M;如果不设置,默认=10M,硬盘缓存的位置沙盒/Library/Caches

    5.2 网络请求的示例代码

      NSURL *url = [NSURL URLWithString:@"http://localhost/photo/1.png"];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

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

      

     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

                if (data) {

                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

                    NSLog(@"%@",dict);

                }

        }];

    注:request有cachePolicy属性,cachePolicy是枚举类型,实际上就"4"个枚举值(2个未实现,1个重复)

        NSURLRequestUseProtocolCachePolicy = 0,  //默认的缓存策略(取决于http协议)

        NSURLRequestReloadIgnoringLocalCacheData = 1,  //忽略缓存,重新请求

        NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, // Unimplemented,苹果未实现

        NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,  //忽略缓存,重新请求

        NSURLRequestReturnCacheDataElseLoad = 2,  //如果有缓存就使用缓存,没有就请求 

        NSURLRequestReturnCacheDataDontLoad = 3,  //始终使用缓存,不请求,适用于应用的离线模式

        NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented,苹果未实现

    5.3 怎么使用NSURLCache管理缓存呢?

      其实5.2里,已经用到了NSURLCache了,  request默认的缓存对象就是这个[NSURLCache sharedURLCache] 全局缓存对象.

      下面5.3的代码,演示可以利用NSURLCache判断 XX请求是否有缓存

      NSURL *url = [NSURL URLWithString:@"http://localhost/photo/1.png"];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

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

     

        NSURLCache *cache = [NSURLCache sharedURLCache];   

        NSCachedURLResponse *response = [cache cachedResponseForRequest:request];

        if (response) {

            NSLog(@"该请求存在缓存");

        }else{

            NSLog(@"该请求不存在缓存");

      }

     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

                if (data) {

                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

                    NSLog(@"%@",dict);

                }

        }];

    5.4 定期清除缓存

      #define weekTime 604800

      NSURL *url = [NSURL URLWithString:@"http://localhost/photo/1.png"];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

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

     

      //发起请求之前,判断当前时间距离最后缓存时间,是否大于7天

      NSDate *lastCacheTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastCacheTime"];

      if([[NSDate date] timeIntervalSinceDate:lastCacheTime] > weekTime){

         [ [NSURLCache sharedURLCache]  removeAllCachedResponses ];  // 删除所有缓存

      }

     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

                if (data) {

                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

                    NSLog(@"%@",dict);

           [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"lastCacheTime"];  //把Now存储为"最后缓存时间"

                }

        }];

    补充: 还可以删除具体的某个请求的缓存  [ [NSURLCache sharedURLCache] removeCachedResponseForRequest:(NSURLRequest *) ]

    6 使用缓存的注意事项:

    1>经常更新的数据,不能用缓存,例如股票,天气预报

    2>偶尔更新的数据,定期更改缓存策略,或清除缓存

    3>大量使用缓存时,需要定期清除缓存

  • 相关阅读:
    Redis Linux版安装详解
    cdh-hbase用户无法执行命令
    异常-java.util.concurrent.TimeoutException: Futures timed out after [100000 milliseconds]
    异常-Caused by: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.security.AccessControlException): Permission denied: user=hdfs, access=WRITE, inode="/hbase":root:supergroup:drwxr-xr-x
    【异常】Maxwell异常 Exception in thread "main" net.sf.jsqlparser.parser.TokenMgrError: Lexical error at line 1, column 596. Encountered: <EOF> after : ""
    【异常】jps6432 -- process information unavailable
    异常-Exception in thread "main" net.sf.jsqlparser.parser.TokenMgrError: Lexical error at line 1, column 596. Encountered: <EOF> after :
    【异常】java.sql.SQLException: Could not retrieve transaction read-only status from server Query
    【异常】ser class threw exception: java.sql.SQLException: The last packet successfully received from the server was 39,444 milliseconds ago. The last
    storedownloadd占用cpu高
  • 原文地址:https://www.cnblogs.com/oumygade/p/4245322.html
Copyright © 2011-2022 走看看