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