【问题标题】:iOS 8 NSURLCache issueiOS 8 NSURLCache 问题
【发布时间】:2015-07-14 00:34:04
【问题描述】:

我正在创建一个应用程序,我希望不时使用缓存的响应。我遇到了一个与 NSURLCache 相关的奇怪问题,更具体地说,如果我在请求中设置 NSURLRequestReturnCacheDataDontLoad,我在 iOS 8 上没有得到缓存响应。这是我与 AFNetworking 一起使用的代码:

// Define web request.
void (^simpleBlock)(void) = ^{
    GTSessionManager.manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

    [GTSessionManager.manager POST:string parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *responseJson = responseObject;

        [self parseJsonSuccess:responseJson];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (error.userInfo[JSONResponseSerializerWithDataKey]) {
            NSData *data = error.userInfo[JSONResponseSerializerWithDataKey];

            NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                                     options:kNilOptions
                                                                       error:&error];

            [self parseJsonError:json];
        }
        else
            [self parseJsonError:nil];
    }];
};

if (self.shouldUseCache) {
    GTSessionManager.manager.requestSerializer.cachePolicy = NSURLRequestReturnCacheDataDontLoad;

    [GTSessionManager.manager POST:string parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *responseJson = responseObject;

        [self parseJsonCacheSuccess:responseJson];

        // Load second request.
        simpleBlock();
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        simpleBlock();
    }];
}
else
    simpleBlock();

这里的主要思想是,如果客户端想要使用缓存,第一个请求应该尝试加载它,将结果传递给处理程序并开始重新加载请求以刷新缓存。

这种方法适用于 iOS 7,但不适用于 iOS 8+。我已经通过以下调用设置了 NSURLCache。

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:500 * 1024 * 1024
                                                            diskCapacity:500 * 1024 * 1024
                                                                diskPath:@"cache" /**Tried nil here as well. */];
[NSURLCache setSharedURLCache:sharedCache];

我阅读了一些关于此的文章和其他 SO 问题,但我无法让它发挥作用。我错过了什么吗?这可能与我使用 POST 请求有关吗?

编辑 忘了提到我没有在我的服务器上使用缓存策略。我还尝试使用Cache-Control=max-age=604800, public 设置缓存策略,但我得到了相同的行为。

【问题讨论】:

    标签: ios caching ios8 afnetworking nsurlcache


    【解决方案1】:

    好的,所以经过进一步调查,我得出的结论是问题出在NSURLSession 的某个地方。我发送了与上面完全相同的请求,但使用 AFHTTPRequestOperation 而不是 AFHTTPSessionManager 并且缓存在 iOS 8+ 上完美加载。

    虽然不太确定问题出在哪里,我认为这与缓存策略有关,但现在我坚持使用NSURLConnection

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-06
      • 2014-11-19
      • 1970-01-01
      • 2014-11-28
      相关资源
      最近更新 更多