AFNetworking, NSURLCache & iOS 6

NSURLCache can be used to define memory and disk caching for URL requests. If you make a connection while you are not connected to the internet with the cache policy set to NSURLRequestReturnCacheDataElseLoad, data should be returned from the cache if it exists. This works as expected on iOS 5 and cached data is always returned. On iOS 6.x, however, this doesn’t happen and the connection will fail returning an error code -1009 which indicates that you are offline. I ran into this recently while using AFNetworking and apparently this is a bug in iOS 6.x and has already been reported to Apple by multiple people.

To workaround this, I wrote a simple class that subclasses AFNetworking‘s AFHTTPClient (thanks to this GitHub issue) and ensures that you always get cached data when it’s available regardless of whether you are connected to the internet or not.

What it does is that it gets the NSCachedURLResponse in the failure block of the request you are making and deserializes it using NSJSONSerialization, then calls the success block with the responseObject as if the connection didn’t fail.

I’ve added the code to a GitHub gist. Please fork it if you think there’s something that could be improved.