6

我正在尝试使用内置于 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 请求?

4

1 回答 1

1

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

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

至于您的第二个问题,您不能保证数据将被 NSURLCache 缓存,即使您的 Cache-Control 标头声明您的内容在很长一段时间内都不会过期。缓存文件始终存储在应用程序的 Caches 目录中,如果 iOS 认为需要释放磁盘空间,可以随时清除该目录。

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

于 2012-11-12T20:54:30.570 回答