IOS Network Request cache: Nsurlcache Detailed

Source: Internet
Author: User

I've read some of the network request caching code for open source projects, basically caching them in the same way that local files are stored. If you're going to add a cache of Web requests to your project, maybe you don't need to build a wheel yourself, and it's enough to solve the Nsurlcache . This article for everyone to receive is iOS development in the Nsurlcache related use, come together to see it.

Cache

First, Nsurlcache provides a comprehensive caching mechanism for both memory and disk. Many articles talk about the need to cache space Settings in appdelegate before using nsurlcache :

-(BOOL) Application: (UIApplication *) application

didfinishlaunchingwithoptions: (nsdictionary *) launchoptions

{

Nsurlcache *urlcache = [[Nsurlcachealloc] initwithmemorycapacity:4 * 1024 * 1024

DISKCAPACITY:20 * 1024 * 1024

Diskpath:nil];

[Nsurlcachesetsharedurlcache:urlcache];

}

However, if you do not add the above code, and run the following code, you can see:

Print(Nsurlcache.sharedurlcache (). diskcapacity)//output://10000000

Print(Nsurlcache.sharedurlcache (). memorycapacity)//output://512000

In other words, the default is to set up 512kb of memory cache space, as well as 10MB of disk cache space. Maybe your code doesn't write anything about Nsurlcache, but it's already silently starting to help you cache.

It's already cached, but how do I use the cache? Please continue down.

caching Policies

GET

don't say much, Nsurlcache It's only for you. GET the request is cached.

Nsurlrequestcachepolicy

There is a property in Nsurlrequest:

public var cachepolicy:nsurlrequestcachepolicy { get }

You can use this property to set the requested cache policy.

public enum nsurlrequestcachepolicy : UInt {

case useprotocolcachepolicy// default value

case reloadignoringlocalcachedata// do not use cached data

case reloadignoringlocalandremotecachedata//unimplemented

public static var reloadignoringcachedata:nsurlrequestcachepolicy { get  }

case returncachedataelseload//whether the cache is expired or not , network requests are made without caching

case returncachedatadontload//cache is cached regardless of expiration, no cache and no network requests

case reloadrevalidatingcachedata//unimplemented

}

in fact, a few other values are better understood, but the default value Useprotocolcachepolicy let me not quite understand.

It literally means caching by Protocol's caching policy , then what is this agreement? http protocol .

Detail:RFC 2616, section 13

The server returns a field that has the following in the response header: cache-control:max-age or cache-control:s-maxage , the cache policy is specified by Cache-control, /c5> max-age to indicate the expiration time. The following strategies are adopted based on these field caching mechanisms:

· If the data is not cached locally, a network request is made.

· If there is a local cache and the cache is not invalidated, the cache is used.

· if the cache has expired, ask the server if the data has changed, if it hasn't changed, still use the cache, and if it changes, request new data.

· If the failure is not specified, the system will determine itself whether the cache is invalidated. (usually considered to be an effective time of 6-24 hours)

actually, I used to Cache-control I don't know much about that. t_t, I silently print A bit of the response header, you can see:

print (responseas? nshttpurlresponse)?. Allheaderfields)

// response header:cache-control: no-cache

That's why, though Nsurlcache has been silently cached, but I do not feel, of course, you may not be the same there. This No-cache means that it is not cached.

here to add an extra sentence, see the online students say that they have a request data has been used in the cache, has not been updated. This may be the Cache-control error returned by the server .

Open the sandbox path under the Library/caches , you can see the cache file:


This can indicate that the data on the disk exists in the database, and performance is not a concern. Open the database file to see the requested data.


in the Cfurl_cache_response table you can see that there is a field that is Request_key , through which the values inside can infer that each response is requested by the The url+ parameter is stored as key.

of course, after many trials of mine, in Cache-control:no-cache , Nsurlcache also caches, but does not use cached data.

To summarize: By default The Nsurlcache cache policy is based on the HTTP protocol, and the server tells Nsurlcache by the Cache-control:max-age field Whether the data needs to be cached.

Cache Encapsulation

If you do not plan to use the HTTP protocol cache policy, you can still use nsurlcache for caching.

public Funccachedresponseforrequest (request:nsurlrequest), Nscachedurlresponse?

You can use this method to get the cache by passing in the request. nscachedurlresponse saved the last requested data and the response header.

public funcstorecachedresponse(cachedresponse: Nscachedurlresponse, Forrequestrequest: Nsurlrequest)

the nsurlsessiondelegate Protocol has the following methods, you can modify the data to be cached, add userInfo, in the proxy method must call Completionhandler, the data that will be cached is passed in, and if you pass nil it means no cache.

optionalpublic funcurlsession(session: Nsurlsession,

datatask: Nsurlsessiondatatask,

willcacheresponseproposedresponse: Nscachedurlresponse,

completionhandler: (nscachedurlresponse?), Void)

This can be written in alamofire :

Alamofire.manager

. sharedinstance

. Delegate

. Datataskwillcacheresponse = {(Session, task, Cachedresponse), Nscachedurlresponse? in

var userInfo = [Nsobject:anyobject] ()

// set userInfo

return Nscachedurlresponse (Response:cachedResponse.response,

Data:cachedResponse.data,

Userinfo:userinfo,

StoragePolicy:cachedResponse.storagePolicy)

}

Source: Bole Online



IOS Network Request cache: Nsurlcache Detailed

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.