iOS - 缓存如何工作?

时间:2015-11-14 04:10:45

标签: ios swift caching nsurlcache

我正在开发一个代表来自Web API的JSON的应用程序。

远程源每天更新几次。

我想做的就是:

// pseudo code

makeRequest() {   
 if (network not available){

  if (cache not exists) {
      showEmptyScreen()
  }else if (cache exists){
      useCache()
  }

 }else if (network available){

    if (cache not exists) {   
        loadFromRemote()
    }else if (cache exists){
        if (cache is older than latest update) {
           loadFromrRemote()
        }else {
           useCache()
        }
    } 
 }
}

我从AppleNSHipster了解了NSURLCache

如果NSURLCache可以做我想做的事,那仍然令人困惑。例如,如何在没有真正下载任何内容的情况下检查是否有更新版本的数据?

如果NSURLCache无法处理检查,我怎么能自己编码呢?

感谢您的任何建议!

1 个答案:

答案 0 :(得分:1)

缓存的行为主要取决于您和您的服务器。 <?php //This is for the images $results = $connecDB->prepare("select image,caption,id from gallery order by id desc LIMIT $start, $limit "); $results->execute(); $results = $results->fetchAll(); foreach($results as $results) { $pid=$results["id"]; ?> <div class="item" id="item-<?php echo $results['id']?>"> <p><img src="../upload/images/<?php echo $results['image']?>" height="500px" width="500px" /></p> <p><?php echo $results['caption']?></p> <?php //This is for the comments $re= $connecDB->prepare("select * from comments where pid = :pid order by id"); $re->bindParam(':pid', $pid); $re->execute(); foreach($re as $re) { $name=$re["name"]; $comment=$re["comment"]; ?> <div class="large-2 columns small-3"><font color="#3366ff"><?php echo $name?></font></div> <div class="large-10 columns"><p><?php echo $comment?></p></div> <?php}?> </div> <?php}?> 除了超出其容量限制时可能做什么之外,不会自行做出决定。

当您发出请求时,NSURLCache之类的标题将通过比较缓存数据的时间戳来确定数据是否已传输。

基于服务器的标头(例如If-Modified-Since)也会影响数据在缓存中保持有效的时间。

总之,Cache-Control可以处理您的需求,但实现将基于NSURLCache的配置,您如何发出请求,如何在响应中实现缓存控制以及您是否覆盖标题给出的策略。

相关问题