Difference between NSURLSession and NSURLConnection, nsurlsession

Source: Internet
Author: User
Tags key string

Difference between NSURLSession and NSURLConnection, nsurlsession
Note: This article searches Baidu for "NSURLSession and NSURLConnection differences" to find the information. It is only for your own learning and understanding. It is not original and would like to indicate the source, however, I found that many articles with the same content do not know who is the true author, so I will not state the source! Here, I would like to say thank you to the real author. Thank you for sharing it! 1. Usage Status NSURLSession is a replacement for NSURLConnection. It was released with ios7 at the Apple global Developer Conference (WWDC2013) in 2013. It is a new network access interface after NSURLConnection is reconstructed and optimized. From iOS9.0, the two methods used to send the request in NSURLConnection have expired (synchronous request, asynchronous request), and the method used to initialize the network connection (initWithRequest: delegate :) has also been set to expired, we recommend that you use NSURLSession to send network requests. 2. General tasks and upload NSURLSession provide special solutions for complex network operations such as download/upload. For general, upload, and download, they correspond to three different network request tasks: NSURLSessionDataTask, NSURLSessionUploadTask and NSURLSessionDownloadTask .. The created tasks are all suspended and need to be executed by resume. When the data returned by the server is small, there is no difference between the NSURLSession and NSURLConnection in the procedure of executing a common task. When an upload task is executed, the NSURLSession and NSURLConnection must also set the request body of the post request for upload. 3. When downloading a file using NSURLConnection, first download the entire file to the memory and then write it into the sandbox. If the file is large, the memory will soar. When NSURLSessionUploadTask is used to download files, the files will be downloaded to the tem folder in the sandbox by default, and the memory will not soar. However, after the download is complete, the temporary files in the tem will be deleted, you need to add the code to save the file in the completionHandler callback when initializing the task method. The following code saves the downloaded file to the caches folder of the sandbox when instantiating a network download task:

[Register [NSURLSessionDownloadTask * task = [session downloadTaskWithURL: [NSURL URLWithString: @ "http: // 192.168.1.17/xxxx.zip"] completionHandler: ^ (NSURL * _ Nullable location, NSURLResponse * _ Nullable response, NSError * _ Nullable error) {// obtain the caches path of the sandbox NSString * path = [[response (NSCachesDirectory, NSUserDomainMask, YES) lastObject] response: @ "xxx. dmg "]; // generate the URL path NSURL * url = [NSURL fileURLWithPath: path]; // save the file to the specified file directory [[NSFileManager defaultManager] moveItemAtURL: location toURL: url error: nil] ;}] resume];
4. The NSURLConnection instantiation object is controlled by the request method. When the instantiation starts, the default request is sent (synchronously sent) and the start method is not required. However, cancel can stop sending requests and cannot continue accessing the requests after they are stopped. You need to create a new request. The NSURLSession has three control methods: cancel (cancel), pause (suspend), and resume (resume). After being paused, You can resume the current request task. 5. The NSURLConnection method is used for resumable download. By setting the Range attribute of the HTTPHeaderField of the access request, the running loop is enabled. The NSURLConnection proxy method is used as the event source of the running loop, in the era of receiving and downloading data, the processing method will be continuously called and the NSOutputStream pipeline stream will be used for data storage. NSURLSession is used for breakpoint download. After the download task is paused, if downloadTask is not empty, call cancelByProducingResumeData :( void (^) (NSData * resumeData) completionHandler, this method receives a parameter to complete processing of the code block. This code block has an NSData parameter resumeData. If resumeData is not empty, we will save this object to the View Controller's resumeData attribute. When you click Download again, you can continue the download by calling [[self. session downloadTaskWithResumeData: self. resumeData] resume. After comparison, we can find that it is more convenient to use NSURLSession for breakpoint download. 6. In the NSURLSession Constructor (sessionWithConfiguration: delegate: delegateQueue), a parameter of the NSURLSessionConfiguration class can be used to set the configuration information, which determines the cookie, security, and high-speed cache policies, maximum number of host connections, resource management, and network timeout. NSURLConnection does not support this configuration. Compared with NSURLConnection, NSURLConnection depends on a global configuration object. Due to lack of flexibility, NSURLSession has greatly improved. NSURLSession can be configured with three types of configuration information: + (NSURLSessionConfiguration *) defaultSessionConfiguration. The configuration information uses the hard disk-based persistent session Cache, save your certificate to the key string and store it using shared cookies. + (NSURLSessionConfiguration *) ephemeralSessionConfiguration. The configuration information is roughly the same as that of default. Besides, the cache, certificate, or any Session-related data will not be stored on the hard disk, but stored in the memory. The lifecycle is consistent with that of the Session. For example, you can use the web browser without trace browsing and other functions based on this. + (NSURLSessionConfiguration *) backgroundSessionConfigurationWithIdentifier :( NSString *) identifier, configuration information allows you to create a session that can still transmit data in the background or even when the APP is disabled. Note that the background Session must be assigned a unique identifier when it is created, so that the APP can be differentiated based on identifier when it is run next time. If the APP is disabled, the IOS system will close all background sessions. In addition, the IOS system does not automatically wake up the APP after it is forcibly disabled by the user. Data Transmission will continue only when the user starts the APP next time.

Related Article

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.