尝试从磁盘访问缓存请求时NSURLCache返回nil

bog*_*gen 6 iphone xcode caching ios5 afnetworking

我正在尝试使用iOS 5中内置的基于磁盘的url cacing.我有一个json feed,我想加载然后缓存,所以它会在下次用户使用应用程序时立即加载.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.
Run Code Online (Sandbox Code Playgroud)

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

[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;
    }];
Run Code Online (Sandbox Code Playgroud)

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

jat*_*ben 1

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

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

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

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