NSURLCache returning nil when trying to access cached request from disk NSURLCache returning nil when trying to access cached request from disk xcode xcode

NSURLCache returning nil when trying to access cached request from disk


When you attempt to fetch the cached response in your first code section (line 9), the request has not completed yet.

-[AFJSONRequestOperation JSONRequestOperationWithRequest:success:failure:] is asynchronous, so nothing will be stored in the cache until the request completes. If you try to fetch the cached response inside the success block (or in a cache response block, as you did in your second code section), it should work correctly.

As to your second question, you can't guarantee that the data will be cached by NSURLCache, even if your Cache-Control headers state that your content shouldn't expire until far in the future. The cache file is always stored in your app's Caches directory, which can be cleared by iOS at any time if it thinks it needs to free up disk space.

If you need to make sure your JSON data is always available, save it yourself in your app's Library/Application Support directory, ideally with the NSURLIsExcludedFromBackupKey specified (unless your app truly cannot function without the data).