In IOS application development, in order to reduce the number of interactions with the server and speed up user response, a cache mechanism is generally added to the IOS device. The purpose of using cache is to enable the application to respond to user input faster and to run the program efficiently. Sometimes we need to cache the data obtained by the remote web server to reduce multiple requests to the same url. The following will introduce how to cache in an IOS device.
Memory cache We can use the NSURLCache class in sdk. NSURLRequest needs a cache parameter to explain how the url it requests is like cached data. Let's first look at its CachePolicy type.
1. NSURLRequestUseProtocolCachePolicy The default cache policy of NSURLRequest is defined using the Protocol protocol.
2. NSURLRequestReloadIgnoringCacheData Ignore cache and download it directly from the original address.
3. NSURLRequestReturnCacheDataElseLoad Download from the original address only if data does not exist in the cache.
4. NSURLRequestReturnCacheDataDontLoad Only uses cache data. If cache does not exist, the request fails; it is used to offline mode without establishing a network connection;
5. NSURLRequestReloadIgnoringLocalAndRemoteCacheData: ignores local and remote cache data and downloads directly from the original address. It is similar to NSURLRequestReloadIgnoringCacheData.
6. NSURLRequestReloadRevalidatingCacheData: Verify whether the local data is the same as the remote data. If it is different, download the remote data, otherwise use the local data.
Some common methods and attributes://Get the cache management object of the current application
+ (NSURLCache *)sharedURLCache;
//Set custom NSURLCache as application cache management object
+ (void)setSharedURLCache:(NSURLCache *)cache;
//Initialize an application cache object
/*
memoryCapacity Set memory cache capacity
diskCapacity Set disk cache capacity
path disk cache path
Content cache will be cleared after the application exits. Disk cache will not
*/
- (instancetype)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(nullable NSString *)path;
//Get the cache for a request
- (nullable NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;
//Set the specified cache for the request
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request;
//Remove the cache of a request
- (void)removeCachedResponseForRequest:(NSURLRequest *)request;
//Remove all cached data
- (void)removeAllCachedResponses;
//Remove cache settings from a certain time
- (void)removeCachedResponsesSinceDate:(NSDate *)date NS_AVAILABLE(10_10, 8_0);
//Memory cache capacity size
@property NSUInteger memoryCapacity;
//Disk cache capacity size
@property NSUInteger diskCapacity;
//The current memory capacity is used
@property (readonly) NSUInteger currentMemoryUsage;
//Current disk capacity
@property (readonly) NSUInteger currentDiskUsage;
Simple example:
#import
@interface ViewController : UIViewController
@property (strong, nonatomic) NSURLConnection *connection;
@property (strong, nonatomic) NSURLCache *urlCache;
@property (strong, nonatomic) NSURL *url;
@property (strong, nonatomic) NSMutableURLRequest *request;
- (IBAction)reloadWebView:(UIButton *)sender;
@end
#import ""
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *paramURLAsString= @"/u/2526279194";
= [NSURLCache sharedURLCache];
[ setMemoryCapacity:1*1024*1024];
//Create a nurl
= [NSURL URLWithString:paramURLAsString];
//Create a request
=[NSMutableURLRequest requestWithURL:
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0f];
[ loadRequest:];
}
In this example, we request a website with url of /u/2526279194. If this url is cached, we get the data directly from the cache, otherwise we get the data again from the /u/2526279194 site. We set the cache size to 1M.
- (IBAction)reloadWebView:(UIButton *)sender {
//Get cached output from the request
NSCachedURLResponse *response =[ cachedResponseForRequest:];
//Judge whether there is a cache
if (response != nil){
NSLog(@"If there is cache output, get data from the cache");
[ setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
}
[ loadRequest:];
= nil;
NSURLConnection *newConnection = [[NSURLConnection alloc] initWithRequest:
delegate:self
startImmediately:YES];
= newConnection;
}
Using the following code, I print out the requested process
- (void) connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response{
NSLog(@"will receive output");
}
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse{
NSLog(@"Request to be sent soon");
return(request);
}
- (void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data{
NSLog(@"Accept data");
NSLog(@"Data length is = %lu", (unsigned long)[data length]);
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse{
NSLog(@"Can output cache");
return(cachedResponse);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"Request Complete");
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error{
NSLog(@"Request failed");
}
@end
The first print result is as follows
2013-01-31 15:28:29.923 NSURLCacheDemo[27848:907] Requests will be sent soon 2013-01-31 15:28:30.043 NSURLCacheDemo[27848:907] Will receive output 2013-01-31 15:28:30.045 NSURLCacheDemo[27848:907] Accept data 2013-01-31 15:28:30.047 NSURLCacheDemo[27848:907] The data length is = 30047 2013-01-31 15:28:30.095 NSURLCacheDemo[27848:907] Accept data 2013-01-31 15:28:30.098 NSURLCacheDemo[27848:907] The data length is = 3575 2013-01-31 15:28:30.102 NSURLCacheDemo[27848:907] Accept data 2013-01-31 15:28:30.104 NSURLCacheDemo[27848:907] The data length is = 1482 2013-01-31 15:28:30.105 NSURLCacheDemo[27848:907] Will cache the output 2013-01-31 15:28:30.107 NSURLCacheDemo[27848:907] Request complete
The second click prints the result as follows
2013-01-31 15:28:31.599 NSURLCacheDemo[27848:907] If there is cache output,Get data from cache 2013-01-31 15:28:31.607 NSURLCacheDemo[27848:907] Requests will be sent soon 2013-01-31 15:28:31.840 NSURLCacheDemo[27848:907] Will receive output 2013-01-31 15:28:31.843 NSURLCacheDemo[27848:907] Accept data 2013-01-31 15:28:31.845 NSURLCacheDemo[27848:907] The data length is = 35104 2013-01-31 15:28:31.846 NSURLCacheDemo[27848:907] Request complete
We see that there is no "output cache" item, and the requested data is the accumulation of the first request, that is, the second time it is to obtain data from memory.