IOS nsurlsessionconfiguration Reference

Source: Internet
Author: User
Tags configuration settings set cookie

IOS nsurlsessionconfiguration Reference

An NSURLSessionConfiguration object-defined behavior and policy is used to NSURLSession upload and download data, and creating a configuration object is always the first step you must take. You can use this object to configure the NSURLSession timeout period, cache policy, connection request, and other types of information for the object you want to use.

Before you use it to initialize an NSURLSession object, it is important to configure your NSURLSessionConfiguration object appropriately. The Session object copies a copy of the configuration settings you provide and uses them to set the session configuration. Once the configuration is complete, the Session object ignores NSURLSeesionConfiguration any changes to the object you are reading. If you want to modify your transfer policy, you must update the session configuration object and use it to create a new NSURLSession object.

Attention:
In some cases, the policy defined in the object in the configuration may be overridden by a policy specified by the object supplied to a task. NSURLRequest Unless the session object's policy is stricter, the policy raised by the request object will be respected. For example, if session configuration > The specified cellular network should not be allowed, the NSURLRequest object will not be able to request a cellular network.

For more information on creating session objects using configuration objects, refer to Nsurlsession Class Reference.

Creating a Session Configuration Object

+ (NSURLSessionConfiguration *)defaultSessionConfiguration

The return value is the configuration object for the new upload and download task that uses the default option. The default session configuration uses a persistent cache that gives the disk (in addition to the results of the download file) and the credentials saved in the user keychain. It also NSURLConnection NSURLDownload stores cookies in the cookie store shared with the class (default).

Note: If you are porting code based on a NSURLConnection class, use this method to get the initial configuration object and then customize this
objects are necessary.

Modifying the returned session configuration object does not affect any future invocation of this method to return the configuration exclusive, and does not alter the existing session default behavior. Therefore, always use a safe return value as a starting point for an additional customization.

+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration

The return value is a session temporary configuration object that does not use persistent storage for caching, cookies, or credentials to optimize the transfer of data and program memory.

A temporary session configuration object is similar to a default session configuration object, except that the session object does not store the cache, the credential store, or any session-related data is stored to disk. A temporary session writing data to disk is the only case when you tell it that a URL is written to the content of a file.

The main advantage of using a temporary session is privacy. If you do not write potentially sensitive data to disk, it is unlikely that the data will be intercepted or used later. For this reason, a short session is perfect for a private web browser and other similar scenarios.

Because a temporary session does not write cache data to the disk, the cache size is limited to the available memory. This restriction means that previously acquired resources are unlikely to be in the cache (and are guaranteed to be in the cache if the user exits and restarts the app). This behavior may reduce perceived performance, depending on your app.

When your application session expires, all temporary sessions will be cleared automatically. Also, in iOS, when your application hangs but is cleaned, when your application is terminated or when your system has memory pressure, the memory cache is not automatically erased.

Note: It is possible to customize a default session configuration object and obtain the same behavior (or any part) provided by a temporary session configuration object, but it is more convenient to use this method

+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier

    • Parameters: Identifier,session The unique identifier of the configuration object, this parameter cannot be an nil empty string

The return value is the session configuration object, which allows HTTP and https uploads and downloads to be performed in the background, and upload and download tasks are performed in a separate process in the system.

Use this method to initialize the configuration object for the application to transfer data files while running in the background. A session configured This object will control the transmission in the system and control the transmission in a separate process. In iOS, this configuration makes the transmission possible even if the app is suspended or terminated.

If an iOS app is terminated and rerun, the app can use the same unique identifier to create a new configuration object and session, and retrieve the transfer status of the process at the end of the program. This behavior applies only to normal termination of a system application: If the user terminates the program from the multitasking screen, the system will cancel the background transfer of all sessions. In addition, the system does not automatically restart the user's own terminated app. The user must explicitly rerun the program before the transfer can start again.

You can configure a background session at the best performance of the system using the discretionay Properties Discretionary transfer task. When transferring large amounts of data, we encourage you to set the value of this property to Yes.

For more information on background uploads and downloading files, please refer to URL Session Programming Guide .

Set general properties

@property(readonly, copy) NSString *identifier

identifierproperty is the unique identifier (read-only) of the background session configuration object.

This property is assigned only backgroundSessionConfigurationWithIdentifier: when the configuration object is created using the method. This string uniquely identifies the background session object. In iOS, you will only use this property if the app is terminated and the transfer is taking place in the background. When the application is restarted, use this string to recreate and transfer the configuration object and session.

@property(copy) NSDictionary *HTTPAdditionalHeaders

HTTPAdditionalHeadersproperty is the additional no dictionary that is sent by the request.

This property specifies an additional header that is added to all tasks based on this configuration. For example, you can set the UserAgent header by using a session based on this configuration, and your app will automatically be included in each request.

An NSURLSession object is designed to handle all aspects of the HTTP protocol for you. In this way, you should not modify the title:

    • Authorization

    • Connection

    • Host

    • Www-authenticate

In addition, if you can automatically determine the length of the uploaded data body, for example, if you provide an NSData object's content body, Content-Length the length of the content length () is set by yourself.

@property NSURLRequestNetworkServiceType networkServiceType

networkServiceTypeproperty provides the type of network service.

This attribute determines the type of network service that is configured on this basis for all tasks of the session.

The type of network service provides a hint about the purpose of the system's underlying traffic. This implies that the system optimizes the flow of traffic to determine the ability to wake up cellular Wi-Fi radios with multiple blocks of speed. By providing accurate information, it improves the system's ability to optimally balance battery life, performance and other considerations.

For example, if your app is performing a download that does not require a user request, you should specify NSURLNetworkServiceTypeBackground , for example, pre-read content so that he can view it when the user chooses to view it.

This setting can also affect the Wi-Fi quality (QoS) priority of the service.

The default value is NSURLNetworkServiceTypeDefault .

@property BOOL allowsCellularAccess

allowsCellularAccessThe property is a Boolean value that is used to determine whether the connection is through a cellular network.

This property controls whether the session task is configured to allow connections over a wireless network based on this session.

The default value is yes.

For more information, please read Restrict Cellular Networking Correctly .

@property NSTimeInterval timeoutIntervalForRequest

timeoutIntervalForRequestThe Timeout property represents the time-out interval used when waiting for more data to be used.

This attribute determines the time-out interval for all task requests based on the session of this configuration. The request time-out interval controls the length of time (in seconds) that a task should wait for additional data to arrive before it is discarded. When the new data arrives, the timer associated with the value will be reset. A timeout is triggered when the request timer reaches the specified time interval without receiving any new data.

The default value is 60 seconds.

Important: If the original request fails to cause a timeout, any upload or download tasks created by the background session will be retried automatically. To configure how long the upload or download task takes to be allowed to retry or transfer, use the timeoutIntervalForResource attribute.

@property NSTimeInterval timeoutIntervalForResource

timeoutIntervalForResourceProperty represents the maximum request time that a resource request should be allowed.

This attribute determines the resource time-out interval for all tasks based on the session of this configuration. The resource time-out interval controls the length of time (in seconds) to wait before a resource is discarded. When the request is initialized, the resource timer starts and counts, knowing the request for the Citadel or reaching the timeout interval, starting with the first-to-the-resource timer.

The default value is 7 days.

@property(copy) NSString *sharedContainerIdentifier

sharedContainerIdentifierThe property identifies a shared container for the file that the background URL session should be downloaded from.

To create love for an app extension you have a URL session, you have to set a valid identifier for the application extension and the day you go to apply.

Important: If you try to create a URL session using your application extension, but you cannot set this property to a valid value, the URL session will be invalidated at the time of creation.

For more information on application extensions, please refer to App Extension Programming Guide .

Set Cookie Policy

@property NSHTTPCookieAcceptPolicy HTTPCookieAcceptPolicy

HTTPCookieAcceptPolicyproperty, a policy constant that determines when cookies should be accepted.

This property determines the cookie acceptance policy for all tasks of the session based on this configuration.

The default value for this is NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain . You can change it to any NSHTTPCookieAcceptPolicy constant that is defined on the enumeration type.

If you want more direct control over what cookies are accepted, set it to the value for NSHTTPCookieAcceptPolicyNever , and then use allHeaderFields and cookiesWithResponseHeaderFields:forURL: method to extract cookies from the URL response object yourself.

@property(retain) NSHTTPCookieStorage *HTTPCookieStorage

HTTPCookieStorageproperty determines the use of cookie storage objects for all tasks that are based on this configuration session.

To disable cookie storage, set the property to nil .
For the default and background sessions, the default value is the shared cookie store object.

For a temporary session, the default value is a private cookie store that is designed to store data in memory and is destroyed when the session is invalid.

@property BOOL HTTPShouldSetCookies

HTTPShouldSetCookiesproperty is a Boolean value used to determine whether the request should contain cookies in the cookie store.

This property controls which cookies in the shared Co store should be provided automatically when all task requests are based on this configuration.

If you want to provide cookies yourself, set the value to no, and provide either a cookie header that passes through the session's HTTPAdditionalHeaders properties or the NSURLRequest level of each request using the custom object.

The default value is yes.

Set security level

@property SSLProtocol TLSMaximumSupportedProtocol

TLSMaximumSupportedProtocolThe maximum TLS protocol version that the client should request when Sesssion is connected.

This attribute determines the maximum TLS protocol version for all tasks that are based on the session of this configuration.

The default value is the latest version of TLS supported by the system (currently TLS1.2 or kTLSProtocol12). Additional values for the SSL protocol refer to the enumeration constants of the SSL protocol.

@property SSLProtocol TLSMinimumSupportedProtocol

TLSMinimumSupportedProtocolattribute, the minimum TLS protocol that should be accepted during the protocol negotiation process.

This attribute determines the minimum TLS protocol version for all tasks configured on the session basis.

The default value is SSL 3.0 (KSSLPROTOCOL3). For additional values, refer to the SSL protocol constant enumeration type.

@property(retain) NSURLCredentialStorage *URLCredentialStorage

URLCredentialStorageproperty, a credential store provides credentials for authentication.

This property determines that the task credential store object is used in the configuration session on this basis.

To not use the credential store, set this property to nil .

For the default and background session, the default value is the shared credential store object.

For a temporary session, the default value is the private credential store object, which stores the data only in memory and when the invalid session is destroyed.

Set Cache Policy

@property(retain) NSURLCache *URLCache

URLCacheThe cache response is requested in the session property, which is provided by the URL cache.

This property determines the URL cache object that is configured on this basis for all tasks in the session.

To disable caching, set this property to nil .

For the default session, the default value is the shared URL cache object.

For background session, the default value is zero.

For a temporary session, the default value is a dedicated cache object that stores data only in memory when an invalid session is destroyed.

@property NSURLRequestCachePolicy requestCachePolicy

requestCachePolicyproperty that determines when a constant of the response is returned from the cache.

This property determines the task request caching policy used in the session to be configured on this basis.

Setting this property to one of the NSURLRequestCachePolicy defined constants Specifies whether the cache policy should depend on the expiration date and age, whether the cache should be completely disabled, and whether the server should contact to determine whether the content has been changed since it was last requested.

The default value is NSURLRequestUseProtocolCachePolicy .

Background transfer support

@property BOOL sessionSendsLaunchEvents

sessionSendsLaunchEventsProperty, a Boolean value that indicates whether the app should be replied to or started in the background when the transfer ends.

For backgroundSessionConfigurationWithIdentifier: configuration objects created using the method, you can use this property to control the startup behavior for iOS apps. This property is ignored when you create a configuration object using another method.

The default value for this property is Yes, and the iOS app is automatically awakened when the session task completes or requires authentication when the value of this property is yes. At that time, the system invokes the application's delegate request application:handleEventsForBackgroundURLSession:completionHandler: method, giving it a session identifier that needs attention. If your application must be restarted, you can use that identifier to create a new configuration and session object that can serve the task.

@property(getter=isDiscretionary) BOOL discretionary

discretionaryProperty, a Boolean value that determines whether background tasks can be scheduled at the best performance of the system:

For backgroundSessionConfigurationWithIdentifier: configuration objects created using the method, use this property to control the system when the transfer occurs. Configuration objects created using other methods ignore this property.

When transferring large amounts of data, we encourage you to set this property to Yes, which is best when the system dispatches these transmissions. For example, when transferring large amounts of data, the system may be delayed, knowing that device insertions will connect to Wi-Fi. The property defaults to No.

The Session object requests the value of this property only when your app starts transmitting in the foreground. For the application transfer in the background begins, the system always starts to pool its discretionary power, in other words, the system is established this property is yes and ignores any values you specify.

Support for custom protocols

@property(copy) NSArray <Class> *protocolClasses

protocolClassesAn array of additional protocol subclasses that handle the request in the session property.

The objects in this array correspond to the custom subclass objects that you define NSURLProtocol .

Before you process the request, an NSURLSession object searches for the default protocol, and then checks your custom protocol until it finds one that can handle the specified request. The protocol it uses canInitWithRequest: returns YES through the class method, indicating that the class is able to handle the specified request.

Note that you cannot use a custom subclass in a session that is in the background session NSURLProtocol .

The default value is an empty array.

Setting HTTP policy and Proxy properties

@property NSInteger HTTPMaximumConnectionsPerHost

HTTPMaximumConnectionsPerHostProperty that uses the maximum number of simultaneous connections for a given host.

This attribute determines the maximum number of simultaneous connections that can be made to the task per host for the session based on this configuration.

This limit is per session, so if you use multiple sessions, your application as a whole may exceed this limit. Also, depending on your connection to the Internet, a sess may use a lower lower limit than you specify.

The default value is OS X 6, iOS 4.

@property BOOL HTTPShouldUsePipelining

HTTPShouldUsePipeliningProperty, a Boolean value that determines whether the session should use an HTTP delivery path.

This property determines whether the task in the session should use an HTTP delivery path based on this. You can also enable the NSURLRequest delivery path on a per-person basis by using objects.

The default value is No.

@property(copy) NSDictionary *connectionProxyDictionary

connectionProxyDictionaryproperty, which is used in this session to include the Dictionary of proxy information.

When connected to a remote host, this property controls the agent task for the session based on this configuration.
The default value is, which means that the NULL task uses the default system settings.

Refer CFProxySupport Reference to learn more about this dictionary.

IOS nsurlsessionconfiguration Reference

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.