Nsurlcache data Cache Class usage resolution in IOS _ios

Source: Internet
Author: User

In iOS application development, in order to reduce the number of interactions with the server, speed up the user's response speed, the iOS device will generally add a caching mechanism. The purpose of using caching is to use the application to respond more quickly to user input, and to run the program efficiently. Sometimes we need to cache the data obtained by the remote Web server and reduce multiple requests to the same URL. The following describes how to cache in an iOS device.

Memory cache We can use the Nsurlcache class in the SDK. Nsurlrequest needs a cache parameter to describe the URL it requested to cache the data, we first look at its cachepolicy type.

1, nsurlrequestuseprotocolcachepolicy nsurlrequest default cache policy, using the Protocol protocol definition.

2, Nsurlrequestreloadignoringcachedata ignore the cache to download directly from the original address.

3, Nsurlrequestreturncachedataelseload only in the cache does not exist when data from the original address download.

4, Nsurlrequestreturncachedatadontload only use the cache data, if there is no cache, the request failed, for the network connection is not established offline mode;

5, Nsurlrequestreloadignoringlocalandremotecachedata: Ignore local and remote cache data, directly from the original address download, Similar to the nsurlrequestreloadignoringcachedata.

6, Nsurlrequestreloadrevalidatingcachedata: Verify that local data and remote data are the same, if different then download remote data, otherwise use local data.

some common methods and properties:
Get the cache management object that is currently applied
+ (Nsurlcache *) Sharedurlcache;
To set the custom Nsurlcache as an application cache management object
+ (void) Setsharedurlcache: (Nsurlcache *) cache;
Initializes an application cache object
/*
Memorycapacity set Memory Cache capacity
Diskcapacity Set Disk cache capacity
Path disk cache paths
The content cache empties the disk cache after the application exits without
*/
-(Instancetype) Initwithmemorycapacity: (Nsuinteger) memorycapacity diskcapacity: (nsuinteger) diskCapacity DiskPath :(Nullable NSString *) path;
Gets the cache of a request
-(Nullable Nscachedurlresponse *) Cachedresponseforrequest: (nsurlrequest *) request;
Set the specified cache to the request
-(void) Storecachedresponse: (Nscachedurlresponse *) cachedresponse forrequest: (nsurlrequest *) request;
Remove cache for a request
-(void) Removecachedresponseforrequest: (nsurlrequest *) request;
Remove all cached data
-(void) removeallcachedresponses;
To 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;
Current used memory capacity
@property (readonly) Nsuinteger currentmemoryusage;
Currently used 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 "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

-(void) viewdidload
{
[Super Viewdidload];
NSString *paramurlasstring= @ "http://blog.sina.com.cn/u/2526279194";
Self.urlcache = [Nsurlcache Sharedurlcache];

[Self.urlcache setmemorycapacity:1*1024*1024];
Create a Nsurl
Self.url = [Nsurl urlwithstring:paramurlasstring];
Create a request
Self.request=[nsmutableurlrequest RequestWithURL:self.url
Cachepolicy:nsurlrequestuseprotocolcachepolicy
TIMEOUTINTERVAL:30.0F];
[Self.mywebview LoadRequest:self.request];
}


In this example, we request a URL for a http://blog.sina.com.cn/u/2526279194 Web site. If the URL is cached, we get the data directly from the cache, or we retrieve the data from the http://blog.sina.com.cn/u/2526279194 site. We set the cache size to 1M.


- (IBAction)reloadWebView:(UIButton *)sender {

Get the cached output from the request
Nscachedurlresponse *response =[self.urlcache CachedResponseForRequest:self.request];
Determine if there is a cache
if (response!= nil) {
NSLog (@ "Fetch data from cache if there is cache output");
[Self.request Setcachepolicy:nsurlrequestreturncachedatadontload];
}
[Self.mywebview LoadRequest:self.request];

Self.connection = nil;

Nsurlconnection *newconnection = [[Nsurlconnection alloc] InitWithRequest:self.request
Delegate:self
Startimmediately:yes];
Self.connection = newconnection;
}

Using the following code, I will print out the requested procedure
-(void) connection: (Nsurlconnection *) connection
Didreceiveresponse: (Nsurlresponse *) response{
NSLog (@ "will receive output");
}
-(Nsurlrequest *) connection: (Nsurlconnection *) connection
Willsendrequest: (nsurlrequest *) request
Redirectresponse: (Nsurlresponse *) redirectresponse{
NSLog (@ "will send Request");
return (request);
}
-(void) connection: (Nsurlconnection *) connection
Didreceivedata: (NSData *) data{
NSLog (@ "Accept data");
NSLog (@ "Data length =%lu", (unsigned long) [data length]);
}
-(Nscachedurlresponse *) connection: (Nsurlconnection *) connection
Willcacheresponse: (Nscachedurlresponse *) cachedresponse{
NSLog (@ "will cache output");
return (Cachedresponse);
}
-(void) connectiondidfinishloading: (nsurlconnection *) connection{
NSLog (@ "request Complete");
}
-(void) connection: (Nsurlconnection *) connection
Didfailwitherror: (Nserror *) error{
NSLog (@ "request failed");
}

@end

The first time the results are printed as follows

2013-01-31 15:28:29.923 nsurlcachedemo[27848:907]
is about to send a request 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] Data length = 30047
2013-01-31 15:28:30.095 nsurlcachedemo[27848:907] Accept data
2013-01-31 15:28:30.098 27,848:907] Data length for = 3575
2013-01-31 15:28:30.102 nsurlcachedemo[27848:907] Receive data
2013-01-31 15:28:30.104 nsurlcachedemo[27848:907] Data length = 1482
2013-01-31 15:28:30.105 nsurlcachedemo[27848:907] will cache output
2013-01-31 15:28:30.107 nsurlcachedemo[27848:907] Request complete

The second time you click the print result is as follows

2013-01-31 15:28:31.599 nsurlcachedemo[27848:907] If there is a cached output, fetch the data from the cache
2013-01-31 15:28:31.607 nsurlcachedemo[ 27,848:907] Upcoming request
2013-01-31 15:28:31.840 nsurlcachedemo[27848:907] will receive output from
2013-01-31 15:28:31.843 NSURLCACHEDEMO[27848:907] Accept data
2013-01-31 15:28:31.845 nsurlcachedemo[27848:907] Data length = 35104
2013-01-31 15:28:31.846 nsurlcachedemo[27848:907] Request complete

We see no "cache output", and the requested data is the accumulation of the first request, which is the second time the data is fetched from memory.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.