URL Loading System----ios engineer must be proficient in mastering

Source: Internet
Author: User

URL Loading System----ios engineer must be proficient in mastering  iOS relies on the web-whether it's reading and writing data from the server, distributing computing tasks to the system, or loading pictures, audio, video, etc. from the cloud.  

When an application is faced with a decision to deal with a problem, it usually chooses the highest-level framework to solve the problem. So if the given task is through http://, https:// or communicating ftp:// , then the NSURLConnection relevant method is the best choice. Apple has a wide range of Web-based classes, from URL loading, to save management, to authentication and storage cookies, to meet the needs of modern OBJECTIVE-C application development:

URL loading
Nsurlconnection
Nsurlrequest Nsmutableurlrequest
Nsurlresponse Nshttpurlresponse
Cache Management
Nsurlcache
Nscacheurlrequest
Nscachedurlresponse
Certifications & Certificates
Nsurlcredential
Nsurlcredentialstorage
Nsurlauthenticationchallenge
Nsurlprotectionspace
Cookie Storage
Nshttpcookie
Nshttpcookiestorage
Protocol support
Nsurlprotocol

Although the URL loading system contains a lot of content, but the code is designed to be very good, not to expose complex operations, developers only need to use the time to set. Any NSURLConnection requests made through the system are intercepted by other parts of the systems, which makes it possible to explicitly load the cache from the hard disk when available.

Speaking of which, let's say: NSURLProtocol .

NSURLProtocolNsurlprotocol is perhaps the most powerful but also the most obscure part of the URL loading system. It is an abstract class that you can subclass to define a new or existing URL loading behavior.

Listen, I said all this crap. If you're not crazy, here are some examples of how you might want to load a request without changing other parts of the code _, for your reference:

Block load request, switch to load from local file

To test the mock and stub of the HTTP return content

Format the header that made the request

To sign a media request that is issued

Create a local proxy service for changes to URL requests when data changes

Intentionally producing malformed or illegally returned data to test the robustness of the program

Filtering sensitive information in requests and returns

Accomplish the realization of the right on the basis of existing agreement and NSURLConnection do not contradict with the original logic

Again NSURLProtocol , the most important point of the core idea: with it, you can change the full details of the URL loading behavior without having to change the rest of the application on the network call.

Let's just say this: NSURLProtocol an apple-allowed man-in-the-middle attack.

    • Sub-class Nsurlprotocol

Previously mentioned NSURLProtocol is an abstract class, so it is not possible to use it directly after the quilt has been used.

    • Let subclasses recognize and control requests

NSURLProtocolthe first task of a subclass is to tell it what type of network request to control. For example, if you want to request a local resource file directly when there is a local resource, the relevant request should correspond to the file name of the existing resource.

This part of the logic is defined in +canInitWithRequest: , and if returned YES , the request is controlled by it. NOthe return jumps directly into the next protocol.

    • Provide request specification

If you want to modify a request in a specific way, you should use the +canonicalRequestForRequest: method. Each subclass should be based on a specification, that is, a protocol should be guaranteed to have only a canonical format (although many different requests may be in the same canonical format).

    • Gets and sets the properties of the request

NSURLProtocolThe Provide method allows you to add, fetch, and delete arbitrary metadata of a request object without requiring private extensions or method spoofing (Swizzle):

    • +propertyForKey:inRequest:

    • +setProperty:forKey:inRequest:

    • +removePropertyForKey:inRequest:

These methods are particularly important when manipulating protocol to perform operations that do not yet give specific information NSURLRequest . These are also useful for state passing between and other methods.

    • Load Request

The most important method of your subclass is the -startLoading -stopLoading . Different custom subclasses call both methods to pass in different content, but the common denominator is to operate around the protocol client.

Each NSURLProtocol subclass instance has a client property that is related to the URL loading system. It is not NSURLConnection , but looks very similar to an object that implements the NSURLConnectionDelegate agreement.

<NSURLProtocolClient>
    • -URLProtocol:cachedResponseIsValid:

    • -URLProtocol:didCancelAuthenticationChallenge:

    • -URLProtocol:didFailWithError:

    • -URLProtocol:didLoadData:

    • -URLProtocol:didReceiveAuthenticationChallenge:

    • -URLProtocol:didReceiveResponse:cacheStoragePolicy:

    • -URLProtocol:wasRedirectedToRequest:redirectResponse:

    • -URLProtocolDidFinishLoading:

In the -startLoading implementation of the and -stopLoading , you need to make a call to client each delegate method at the appropriate time. In simple terms, it is important to call those methods consecutively.

registering subclasses with the URL loading system
    • Finally, in order to use NSURLProtocol subclasses, you need to register with the URL loading system.

When the request is loaded, the system asks each registered protocol: "Hey can you control this request?" "The first +canInitWithRequest: YES protocol to be answered will control the request. The URL protocol will be accessed in the reverse order of the registration sequence, so when called in the -application:didFinishLoadingWithOptions: method [NSURLProtocol registerClass:[MyURLProtocol class]]; , you write your own protocol with a higher priority than the other built-in protocol.

Just like the URL loading system for control requests, NSURLProtocol it is equally powerful and can be used in a variety of flexible ways. As a relatively obscure class, we dug out its potential to make our code more refreshing and robust.


NSURLCache  NSURLCache provides a comprehensive caching mechanism in memory and on-disk for your app's URL requests. As part of the base Class library URL loading system, any NSURLConnection requests that are loaded will be NSURLCache processed.

The network cache reduces the number of requests that need to be sent to the server, while also improving the experience of using the app offline or in a low-speed network.

When a request finishes downloading a response from the server, a cached response is saved locally. The next time the same request is initiated, the locally saved response is returned immediately, and no connection to the server is required. NSURLCachewill return the response automatically and transparently .

    • Initialize and set a shared URL cache

For good use NSURLCache , you need to initialize and set a shared URL cache. This work needs to be done in IOS -application:didFinishLaunchingWithOptions: , while Mac OS X is in –applicationDidFinishLaunching: :

For example:

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions
{
Nsurlcache *urlcache = [[Nsurlcache alloc] Initwithmemorycapacity:4 * 1024 * 1024
DISKCAPACITY:20 * 1024 * 1024
Diskpath:nil];
[Nsurlcache Setsharedurlcache:urlcache];
}

The cache policy is specified separately by the request (client) and the response (server side). Understanding these policies and how they affect each other is key to finding the best behavior for your application.

NSURLRequestCachePolicy  NSURLRequest has a cachePolicy property that specifies the cached behavior of the request based on the following constants:
    • NSURLRequestUseProtocolCachePolicy: Use caching logic implemented in the network protocol for a specific URL request. This is the default policy.

    • NSURLRequestReloadIgnoringLocalCacheData: The data needs to be loaded from the original address. Do not use an existing cache.

    • NSURLRequestReloadIgnoringLocalAndRemoteCacheData: Not only ignore the local cache, but also ignore the proxy server or other intermediate media currently existing, the protocol allows the cache.

    • NSURLRequestReturnCacheDataElseLoad: Use local cache data regardless of whether the cache expires. If no data is requested in the cache, the data is loaded from the original address.

    • NSURLRequestReturnCacheDataDontLoad: Use local cache data regardless of whether the cache expires. If there is no data in the cache for the request, then discarding the data from the original address, the request is considered a failure (that is, "offline" mode).

    • NSURLRequestReloadRevalidatingCacheData: After confirming the validity of the cached data from the original address, the cached data can be used or loaded from the original address.

You are not surprised that these values are not thoroughly understood and often confused.

NSURLRequestReloadIgnoringLocalAndRemoteCacheDataand NSURLRequestReloadRevalidatingCacheData no implementation at all (Link to Radar) deepens the level of chaos!

About NSURLRequestCachePolicy , here's what you actually need to know:

Useprotocolcachepolicy default behavior
Reloadignoringlocalcachedata Do not use caching
Reloadignoringlocalandremotecachedata I was serious, not using any cache
Returncachedataelseload uses the cache (regardless of whether it expires), if not in the cache, load it from the network
Returncachedatadontload Offline Mode: Uses the cache (regardless of whether it expires), but does not load from the network
Reloadrevalidatingcachedata to server authentication before use

    • HTTP Cache semantics

Because it NSURLConnection is designed to support multiple protocols-including FTP , HTTP , HTTPS --The URL loading system specifies the cache in a protocol-independent manner. For the purposes of this article, the cache is interpreted using the term HTTP semantics.

    • HTTP Request and back application
headers to exchange metadata, such as character encoding, MIME type, and cache directives. Request Cache Headers

By default, the NSURLRequest current time is used to determine whether to return cached data. For more precise control, the following request headers are allowed:

If-Modified-Since-This request header corresponds to the Last-Modified response head. Set this value to the value of the field returned at the last request of the same terminal Last-Modified .

If-None-Match-This request header corresponds to the Etag response head. Use the last requested value for the same terminal Etag .

Response Cache Headers

NSHTTPURLResponseContains multiple HTTP headers, and of course includes the following directives to illustrate how the response should be cached:

    • Cache-Control-This header must be specified by the server side to turn on the HTTP caching capability of the client. The value of this header may include max-age (how long to cache), public public or private private , or do not cache no-cache information. For more information, see section of Cache-Control RFC 2616.

In addition Cache-Control , the server may send some additional headers for conditional requests as required (as mentioned in the previous section):

    • Last-Modified-The value of this header indicates the last time the requested resource was modified. For example, a client requests the time line of a recent photo /photos/timeline , and Last-Modified the value can be the time of the most recent photo taken.

    • Etag-this is the abbreviation for "entity tag", which is an identifier that represents the content of the requested resource. In practice, Etag the value can be something like a resource MD5 . This is useful for dynamically generated resources that may not have obvious Last-Modified values.

NSURLConnectionDelegate

Once a response from the server is received, NSURLConnection the agent has the opportunity to -connection:willCacheResponse: specify the cache data in.

NSCachedURLResponseis a class that contains NSURLResponse and is in the cache that corresponds to it NSData .

In -connection:willCacheResponse: , the cachedResponse object is automatically created based on the results returned by the URL connection. Because NSCachedURLResponse there is no mutable part, cachedResponse a new object must be constructed in order to change the value, passing the changed value into–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: returned nil , the response will not be cached.

-(Nscachedurlresponse *) connection: (Nsurlconnection *) connection
Willcacheresponse: (Nscachedurlresponse *) cachedresponse
{
return nil;
}

If you do not implement this method, you NSURLConnection simply use the cache object that you want to pass -connection:willCacheResponse: in, so this proxy method does not have to be implemented unless you need to change some values or block the cache.

    • Precautions

Just like its little partner with no relationship but similar names NSCache , NSURLCache there are some special. In iOS 5, the disk cache starts to support, but only HTTP is supported, not HTTPS (this support is added in iOS 6). Peter Steinberger wrote an excellent article on the subject (http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/ ) to implement his own Nsurlcache subclass (Https://github.com/steipete/SDURLCache) after delving into the details of the interior. Another article by Daniel Pasco on Black Pixel

Http://blackpixel.com/blog/2012/05/caching-and-nsurlconnection.html describes some unexpected default behavior that does not set the cache header when communicating with the server.

NSURLCachereminds us how important it is to be familiar with the systems we are working on. When developing IOS or MAC OS X programs, the heavy weight of these systems is the non-URL Loading system.

Countless developers try to make a simple and fragile system to achieve the function of network caching, NSURLCache as long as the two lines of code can be done and 100 times times better. Even more developers are unaware of the benefits of the network cache and have never tried it, causing their applications to make countless unnecessary network requests to the server. So if you want to see the changes in the world, you want to make sure that you have a program that always opens in the right way, in -application:didFinishLaunchingWithOptions: setting up a shared NSURLCache bar.

   

URL Loading System----ios engineer must be proficient in mastering

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.