【问题标题】:AFNetworking 2.0 AFHTTPRequestOperationManager CachePolicy not workingAFNetworking 2.0 AFHTTPRequestOperationManager CachePolicy 不起作用
【发布时间】:2015-03-27 09:25:39
【问题描述】:

我正在尝试使用 If-Modified-Since 标头向服务器发出 GET 请求,以避免加载相同的内容。当我发出请求时,我知道服务器正在发回 304 指示内容没有更改,但 NSURLCache 或 AFNetworking 正在响应 200 缓存内容。为了防止这种情况,我将请求序列化程序的缓存策略设置为 NSURLRequestReloadIgnoringLocalCacheData,但这并不能解决问题。

- (void)getConfig {

    //Retrive the timeStamp at which the config was last updated
    NSDate *timeStamp = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastGetConfigDate"];

    //Get the rfc1123 representation of the timeStamp
    NSString *dateString = [timeStamp rfc1123String];

    //If we're not force loading the data then include the time stamp in the If-modified-Since header
    [self.requestSerializer setValue:[NSString stringWithFormat:@"%@", dateString] forHTTPHeaderField:@"If-Modified-Since"];

    //Setting cachePolicy to ignore cache data to prevent the cached response
    [self.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];

    //GET REQUEST to /api/config
    [self GET:@"/api/config" parameters:nil success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *jsonDict = (NSDictionary *)responseObject;

        DDLogInfo(@"Config: 200");

        //If the config data was successfully loaded then set the lastGetConfigDate time stamp in the nsuserdefaults to send in the next call with the if-modified-since header
        if (success) {
            [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"lastGetConfigDate"];
        }

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

【问题讨论】:

    标签: ios afnetworking nsurlcache


    【解决方案1】:

    这是最新版本的 AFNetworking 中的一个错误,在 issue #2563 中进行了讨论。 1 月 24 日,尝试解决一些 other issue,引入了这个 bug。要解决它,要么

    • 回滚到之前版本的 AFNetworking 2.5.0;或
    • 自己手动发布 KVO 通知:

      [self.requestSerializer willChangeValueForKey:@"cachePolicy"];
      [self.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
      [self.requestSerializer didChangeValueForKey:@"cachePolicy"];
      

    对这个错误缺乏回应是非常令人失望的。假设这确实是您遇到的问题(尝试上述方法之一,看看它是否可以解决您的问题),请加入我们并在issue #2563 下的讨论中发表您自己的评论。对此表示赞同的人越多,修复的可能性就越大。


    注意:这已于 2015 年 3 月 26 日在提交 7d8e286 中修复。

    【讨论】:

    • 您提出的两个解决方案都解决了这个问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多