OGeek|极客世界-中国程序员成长平台

标题: ios - 如何判断 NSURLCache 是否正常工作? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 02:32
标题: ios - 如何判断 NSURLCache 是否正常工作?

我在我的 App Delegate 中配置了内存和磁盘缓存,但似乎没有使用缓存 - 它似乎每次都进入网络。有没有一种简单的方法来检查数据是否被缓存然后在后续请求中检索?我只需要设置缓存吗?我是否需要通过每次调用 cachedResponseForRequest 或类似的方法来明确检查缓存?它在模拟器上工作吗?我的部署目标是 iOS 6。

谢谢。



Best Answer-推荐答案


几个观察:

  1. 请求必须是可以缓存的(例如 httphttps,但不是 ftp)。

  2. 响应必须生成表明可以缓存响应的 header 。值得注意的是,它必须设置Cache-Control。参见 NSHipster 关于 NSURLCache 的讨论.

    例如下载图片时

    <?php
    
    $filename = "image.jpg";
    
    $lastModified = filemtime($filename);
    $etagFile = md5_file($filename);
    
    header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastModified) . ' GMT');
    header('Etag: "' . $etagFile . '"');
    header('Content-Type: image/jpeg');
    header('Cache-Control: public, max-age=1835400');
    header('Content-Length: ' . filesize($filename));
    
    readfile($filename);
    
    ?>
    
  3. 响应必须满足一些记录不充分的规则(例如,响应不能超过总持久性 NSURLCache 的 5%)。例如,您可以在应用代理的 didFinishLaunchingWithOptions 中放置以下内容:

    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity: 5 * 1024 * 1024
                                                         diskCapacity:20 * 1024 * 1024 diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];
    

    这设置了 5mb 的内存缓存和 20mb 的持久缓存。

  4. 为了完整起见,我会明确说明,在创建 NSURLRequest 时,NSURLRequestReloadIgnoringLocalCacheDataNSURLRequestCachePolicy 会即使响应之前已缓存,也阻止使用缓存。

  5. 在同样的说明中,返回 nilconnection:willCacheResponse: 方法会阻止响应被缓存。

关于ios - 如何判断 NSURLCache 是否正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16346945/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4