📜 ⬆️ ⬇️

Network caching in iOS. NSURLCache

This topic is important when developing any application that interacts with the network. Here, competent use of the system's capabilities can significantly improve user interaction with the program.

NSURLCache is a comprehensive solution for caching network requests in RAM or on disk. In accordance with Apple's documentation , any request using NSURLConnection will be “skipped” through NSURLCache .

Caching reduces the number of necessary calls to the network, improves the impression of working with the program during the complete absence of the Internet or problems with a network connection.

After downloading the server response, its copy is stored in the local cache. The next time you send the same request, the answer will be returned instantly, without accessing the network. NSURLCache returns user data in a transparent manner.
')
To use NSURLCache you need to set the value of the sharedURLCache singleton. You can do this in the application:didFinishLaunchingWithOptions: method on iOS or in applicationDidFinishLaunching: - on Mac OS X:

 -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; [NSURLCache setSharedURLCache:URLCache]; } 

You can manage caching settings - both on the client side and on the server side. Competent choice of options can be useful when optimizing your application.

NSURLRequestCachePolicy


On the server request side, the caching policy is set using the cachePolicy property of the cachePolicy object. You can choose one of the following options:

The differences between these options are not always obvious and often lead to confusion. The fact that NSURLRequestReloadIgnoringLocalAndRemoteCacheData and NSURLRequestReloadRevalidatingCacheData does not add clarity is not added in principle.

What you really need to know about NSURLRequestCachePolicy can be summarized as follows:

HTTP caching


Since the NSURLConnection class NSURLConnection designed to work with various network protocols (including FTP and HTTP / HTTPS), the caching documentation is described in a protocol-independent manner. In this article we will consider it from the point of view of the HTTP protocol.

In HTTP, server request and response headers are used to exchange meta information about coding, MIME types, caching, and so on.

Request headers

By default, NSURLRequest uses the current time to determine whether to return cached information. For more fine-tuning, you can use the following headings:

Response headers

With NSHTTPURLResponse , caching-related headers can also be returned:

In addition to Cache-Control , the server can send additional headers used for conditional data retrieval (see the previous section):

NSURLConnectionDelegate


When processing the result of the request, the delegate of NSURLConnection has the ability to change the cached response using the connection:willCacheResponse: method. An NSCachedURLResponse object is passed to this call, which contains a link to the source NSURLResponse and cached data in the form of NSData . This object is created based on information obtained from a network connection. Since you cannot change instances of the NSCachedURLResponse class, to edit any parameters, you need to create a new object using the initWithResponse:data:userInfo:storagePolicy: initializer initWithResponse:data:userInfo:storagePolicy: for example:

 -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { NSMutableDictionary *mutableUserInfo = [[cachedResponse userInfo] mutableCopy]; NSMutableData *mutableData = [[cachedResponse data] mutableCopy]; NSURLCacheStoragePolicy storagePolicy = NSURLCacheStorageAllowedInMemoryOnly; // ... return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response] data:mutableData userInfo:mutableUserInfo storagePolicy:storagePolicy]; } 

If connection:willCacheResponse: returns nil , the answer will not be cached at all.

 - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { return nil; } 

connection:willCacheResponse: method connection:willCacheResponse: - optional. If it is not implemented in the delegate, an automatically created instance of NSCachedURLResponse will be used.

Underwater rocks


There are several features when working with NSURLCache :

Conclusion


The NSURLCache example once again shows us how important it is to know the capabilities of the system with which you work.

Many developers invent their own bike for organizing caching, because they do not know about the capabilities of NSURLCache , which initialization takes only 2 lines of code and makes the work 100 times more efficient. An even greater number do not even think about the advantages of network caching and do not use it, loading their server with a huge number of unnecessary requests.

Thus, for optimal performance of your application, always initialize NSURLCache in the application:didFinishLaunchingWithOptions: method.

Source: https://habr.com/ru/post/179349/


All Articles