Overview
NSURLConnection is really a complex and convenient class for handling low level connections. Usually, you use NSURLConnection class to establish an FTP/HTTP/HTTPS/FILE connections and get data from remote servers or local files. NSURLConnection aimed to be flexible and handy for some common tasks like redirect/authentication/cache. Also, before iOS 4.0, it adopted delegate design pattern, will send the request to remote server in separated thread automatically.
- NSURLConnection provide both on-disk and in-memory cache.
- There are two types of cache: local cache and remote cache.
- Setting cache policy when create a
NSURLRequest
instance is ONLY for local cache. - Currently only responses to
HTTP
andHTTPS
are cached.
+ (id)requestWithURL:(NSURL *)theURL
+ (id)requestWithURL:(NSURL *)theURL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval
the first method will set the cachePolicy to NSURLRequestUseProtocolCachePolicy
and default timeoutInterval to 60
.
Using NSURLRequestUseProtocolCachePolicy
means a very complex scenario:
From the original document URL Loading System Programming Guide, it says:
The most complicated cache use situation is when a request uses the http protocol and has set the cache policy to NSURLRequestUseProtocolCachePolicy.
If an NSCachedURLResponse does not exist for the request, then the data is fetched from the originating source. If there is a cached response for the request, the URL loading system checks the response to determine if it specifies that the contents must be revalidated. If the contents must be revalidated a connection is made to the originating source to see if it has changed. If it has not changed, then the response is returned from the local cache. If it has changed, the data is fetched from the originating source.
If the cached response doesn’t specify that the contents must be revalidated, the maximum age or expiration specified in the response is examined. If the cached response is recent enough, then the response is returned from the local cache. If the response is determined to be stale, the originating source is checked for newer data. If newer data is available, the data is fetched from the originating source, otherwise it is returned from the cache.
RFC 2616, Section 13 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13) specifies the semantics involved in detail.
When dealing with http://www-origin.sanspo.com/rss/baseball/news/pro-sd.xml
, first it will check the LOCAL cache, then REMOTE cache(may return http status 304), and send back with local cached response and data.