【问题标题】:NSURLCache returning nil when trying to access cached request from diskNSURLCache 在尝试从磁盘访问缓存请求时返回 nil
【发布时间】:2012-11-09 09:44:58
【问题描述】:

我正在尝试使用 iOS 5 中内置的基于磁盘的 url cacing。我有一个 json 提要,我想加载它然后缓存,所以它会在用户下次使用该应用程序时立即加载。 cache.db 文件已成功创建,如果我在 sqlite-editor 中打开它,我可以获取数据。

我正在使用 AFNetworking

NSURL *url = [NSURL URLWithString:@"http://myurl.com/json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSLog(@"%d before call",[[NSURLCache sharedURLCache] currentDiskUsage]);  // logs 0 bytes
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// is successfully loading JSON and reading it to a table view in a view
}failure:nil];

NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request] 
// this returns nil, and can't load the request from disk.

在缓存响应块中,奇怪的是缓存现在正在工作,并且成功地从内存中获取了cacheurl请求。

[operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
        NSCachedURLResponse *cachedResponse_ = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
        NSLog(@"%d AFTER CACHE",[[NSURLCache sharedURLCache] currentDiskUsage]);
        // this writes out 61440
        return cachedResponse;
    }];

下次启动应用程序时如何从磁盘加载缓存的 URL 请求?

【问题讨论】:

    标签: iphone xcode ios5 caching afnetworking


    【解决方案1】:

    当您尝试在第一个代码部分(第 9 行)中获取缓存的响应时,请求尚未完成。

    -[AFJSONRequestOperation JSONRequestOperationWithRequest:success:failure:] 是异步的,因此在请求完成之前不会将任何内容存储在缓存中。如果您尝试在成功块内(或在缓存响应块中,就像您在第二个代码部分中所做的那样)获取缓存的响应,它应该可以正常工作。

    关于您的第二个问题,您不能保证数据会被 NSURLCache 缓存,即使您的 Cache-Control 标头声明您的内容在很久以后才会过期。缓存文件始终存储在您应用的 Caches 目录中,can be cleared by iOS at any time 如果它认为需要释放磁盘空间。

    如果您需要确保您的 JSON 数据始终可用,请将其保存在您应用的 Library/Application Support 目录中,最好是 with the NSURLIsExcludedFromBackupKey specified(除非您的应用确实无法在没有数据的情况下运行)。

    【讨论】:

    • 所以你是说 [NSURLCache sharedURLCache] 不能存储在磁盘上?
    • 不,它可以(并且通常是)存储在磁盘上,但它总是放在Caches 目录中,iOS 随时可能清除该目录。 iOS File System Programming Guide 枚举应用沙箱中可用的目录以及适用于每个目录的规则。
    • 是的,它存储在 Cache.db 中,并且在我重新启动应用程序时不会被清除。所以它应该能够加载缓存。
    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2011-08-17
    • 2011-09-11
    • 1970-01-01
    相关资源
    最近更新 更多