【问题标题】:File Cache between AFNetworking 2.0 and NginxAFNetworking 2.0 和 Nginx 之间的文件缓存
【发布时间】:2014-01-10 15:07:27
【问题描述】:

iOS 客户端:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"host/json/demo.json"
          parameters:parameters
             success:^(AFHTTPRequestOperation *operation, id responseObject) {

             }
             failure:^(AFHTTPRequestOperation *operation, NSError *error) {

             }];

服务器上的 Nginx 配置:

location /json {
          alias    /var/www/json;
          expires 30s;
}

我第一次运行应用程序并正确地从服务器获取 json 数据,然后我修改服务器上的 demo.json,重新启动应用程序,我仍然得到 old json 数据(甚至 30 秒后) , 但是在终端中使用 CURL 推荐我可以获得 new json 数据。我删除应用程序并重新安装它然后我得到 new json 数据。
我的 conf 或代码有问题吗?

【问题讨论】:

    标签: ios json caching nginx afnetworking


    【解决方案1】:

    您的服务器对您的 GET 请求的响应包含 cache-control HTTP headers,导致基础 URL 加载系统缓存您的请求。请参阅NSURLCache Class Reference(和this NSHipster article about it)了解更多信息。

    在调试期间,您可以暂时禁用缓存:

    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0
                                                            diskCapacity:0
                                                                diskPath:nil];
    [NSURLCache setSharedURLCache:sharedCache];
    

    但对于大多数生产应用程序,绝对不推荐使用这种方法,因为缓存对于移动设备上的网络性能非常重要。

    如果存在不应缓存的特定资源,服务器应使用缓存控制标头指示这些资源。

    【讨论】:

      【解决方案2】:

      GET:parameters:success:failure方法默认总是使用缓存,所以我改用自定义AFHTTPRequestOperation不带缓存,像这样:

      NSURL *URL = [NSURL URLWithString:filePath];
      NSMutableURLRequest *request = [[NSURLRequest requestWithURL:URL] mutableCopy];
      [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
      AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
      [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
      
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      
      }];
      [[NSOperationQueue mainQueue] addOperation:op];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-24
        • 1970-01-01
        • 2014-03-29
        • 2014-03-24
        • 2015-05-25
        • 2014-06-04
        • 2015-05-03
        • 2017-08-30
        相关资源
        最近更新 更多