URL Loading System is a series of classes and protocols used to access resources that are located by URL. The core of this technology is to access resources based on the class NSURL. In addition to the class NSURLSession for loading URLS, we divide other related auxiliary classes into 5 classes (as shown in the figure) :

  • Protocol Support
  • Authentication and Credentials
  • Cookie Storage
  • Request Configuration management
  • Cache Management

It is worth mentioning that the Legacy URL Loading System before iOS 7 was based on NSURLConnection.

First, URL loading

The most common class for URL Loading System is NSURLSession, which requests data based on the URL.

The NSURLSession API supports three types of sessions:

  • Default Sessions: Acts like other URL loading methods provided by Foundation, supports disk caching, and saves the credentials to the keychain.
  • Ephemeral Sessions: No data is stored on disk, all caches and credentials are kept in memory only for the session and are cleared once the session is cleared.
  • Background sessions: followdefault sessions“, but also supports data transfer from the vxconfigd process, that is, when the app is suspended, data can continue to be transferred in the background.

Based on NSURLSession, we can create three types of URL loading tasks:

  • Data Tasks: Send and receiveNSDataForm of data. Data Tasks are mainly used to send short, interactive requests. Data Tasks can return Data in batches or all of the Data at once.
  • Download Tasks: Obtain file data and Download the file to the local PC.
  • Upload tasks: send data to the server in the form of files, and also support background download.

Second, auxiliary classes

1. The URL request

NSURLRequest in URL Loading System encapsulates properties related to URL and request protocol.

Support HTTP protocol NSURLRequest/NSMutableURLRequest classes including read/request of setting up, request body, request the first class attribute.

2. The response

The data returned by the server generally consists of two parts:

  • Metadata describing content data: The metadata describing the content data is usually defined by the request protocol. For most protocols, the metadata includes MIME Type, Expected Content Length, text Encoding (where Applicable), and the URL corresponding to the response.
  • Content data itself: that is, data to be requested

The function of NSURLResponse in URL Loading System is to encapsulate metadata and content data itself.

Redirect (change request)

Some protocols, such as HTTP, provide a redirection mechanism: when you make a request and the URL of the resource you requested has changed, the server tells the client that the resource you requested has been moved to the new URL.

We can by implementing relevant agent method URLSession: task: willPerformHTTPRedirection: newRequest: completionHandler:, to intercept redirect events, and decide whether need to redirect to the new address.

4. Authority authentication

Some servers restrict access to certain content and only provide authenticated users with trust certificates. For web servers, protected content is aggregated into an area that requires credentials to access. On the client side, credentials are sometimes needed to determine whether to trust the server to be accessed.

URL Loading System provides classes to encapsulate credentials, encapsulate protected areas, and store secure credentials:

  • NSURLCredential: Encapsulates a credential containing authentication information (such as username and password) and persistent storage behavior.
  • NSURLProtectionSpace: An area of the server that requires credentials to access.
  • NSURLCredentialStorage: Manage the storage of credentials as wellNSURLCredentialAnd the correspondingNSURLProtectionSpaceMapping relationship between.
  • NSURLAuthenticationChallenge: When a client sends a request to a server with restricted access rights, the server queries credential information, including credential information, protected space, authentication error information, and authentication response. This class encapsulates this information.NSURLAuthenticationChallengeInstances are usuallyNSURLProtocolSubclasses are used to notify URL Loading System that authentication is required, as well as inNSURLSessionIs used to handle authentication in the proxy method of

5. Cache management

URL Loading System provides APP-level HTTP response caching. When NSURLSession is used to initiate a request, We can by setting the NSURLRequest and NSURLSessionConfiguration caching strategies (cache policy) to decide whether and how to handle the cache cache. At the same time, we also can realize URLSession: dataTask: willCacheResponse: completionHandler: methods for specific URL Settings cache strategy.

In fact, not all requests can be cached. The URL Loading System currently supports caching only HTTP and HTTPS requests.

The URL Loading System provides the following two classes to manage caching:

  • NSURLCacheThis class allows you to set the cache size and location, as well as read and store each requestNSCachedURLResponse.
  • NSCachedURLResponse: encapsulates request metadata (aNSURLResponseObject) and the actual response content (oneNSDataObject).

NSURLRequest default cache policy is NSURLRequestUseProtocolCachePolicy, Below is a HTTP request adopted NSURLRequestUseProtocolCachePolicy caching mechanism of flow chart (source) :

Cookie storage

URL Loading System provides an APP-level cookie storage mechanism. The two classes involved in cookie operation in URL Loading System are:

  • NSHTTPCookieStorageThis class provides functionality to manage cookie storage.
  • NSHTTPCookie: class used to encapsulate cookie data and properties.

NSURLRequest provides the HTTPShouldHandleCookies attribute to set whether the cookie Manager should automatically handle cookies when the request is initiated. In UIWebView, cookies are automatically cached by the cookie Manager.

Vii. Agreement Support

The URL Loading System supports only HTTP, HTTPS, file, FTP, and data protocols. NSURLProtocol is an abstract class that provides the infrastructure to handle URL loading. By implementing a custom NSURLProtocol subclass, we can enable our app to support a custom data transfer protocol.

Also, the NSURLProtocol core feature is not mentioned in the official documentation, but it is the most important one: with it, you can change all the details of the URL loading behavior without having to change other parts of the application on the network call. Using this, we are free to do as many things as we want, such as:

  • Block image loading requests and load them from local files
  • Load a WebP image in UIWebView
  • Optimize UIWebView preloading by caching static resources
  • UIWebView offline cache
  • Mock and stub HTTP returns for testing purposes
  • Implement an in-APP network packet capture tool

summary

URL Loading System covers all aspects of iOS network programming. Through the above sorting, WE believe that we have had an overall understanding of iOS network programming.

Reference:

  • URL Session Programming Guide
  • URL Loading System – API Reference
  • NSURLProtocol – NSHipster
  • NSURLCache – NSHipster
  • URLSession Tutorial: Getting Started – Ray Wenderlich
  • HTTPS interface encryption and identity authentication
  • [iOS Network Request] – Authentication