Learn how to use NSURLSession

Source: Internet
Author: User

In iOS7, Apple introduced the new API NSURLSession, which is used to replace NSURLConnection.

NSURLSession brings these new benefits:
  • Background upload and download
  • You can pause and continue to connect to the network.
  • Save Configuration
  • Subclass and private storage
  • Improved Authentication Processing
  • Rich Agent models
  • Upload and download through the file system
As a beginner in iOS, I ignore NSURLConnection and directly access NSURLSession. The architecture of NSURLSession is also very simple. NSURLSession itself is a command, and then with a right General NSURLSessionConfiguration, it is responsible for various NSURLSession configurations, and then there is a left general who is responsible for proxy, that is, follow up the status of the boss at any time, and then respond to a certain status point. Finally, there are a bunch of NSURLSessionTask soldiers responsible for completing the actual tasks. In fact, the NSURLSessionTask is also a general reference. It actually involves several types of troops:
  • : For normal data transmission, the obtained data is in the NSData format. You can convert the data according to the original format.
  • : Used for uploading to the Internet
  • : Used for download. This class is a little different from the other two classes. The downloaded content is directly written in a temporary file. After the download, it will give you a pointer to the temporary file, save it manually.
Well, let's start practice. Next we will request an API for bitcoin quotations to obtain their data. Create a project, select Single View Application, and add the following code in ViewController. m:
 - ()initWithCoder:(NSCoder *      self =     NSLog(          NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:          NSURLSession *session =          NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *          (!                          NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *                           (httpResponse.statusCode ==                                   NSString * =                 NSLog(,                    }

1. Package the URL into a request

2. Create a session. Calling sharedSession indicates that the default configuration is used to create a session.
3. When Alibaba Cloud launched the task, Alibaba Cloud NSURLSessionDataTask was directly created from the session, which means that the session calls the dataTaskWithRequest method to complete the network task. Input a request and write a block so that data can be directly processed when the data is downloaded. There are three parameters in the block. data is the data you want to obtain. response Returns some network response information, and error can be used to handle errors.
4. Convert the response type to NSHTTPURLResponse to get the status code.
5. When statusCode is 200, it indicates the network is okay.
6. process the data and print it to the terminal.
7. Of course, the most important thing is not to call this resume to start downloading when completing the above steps.

Since storyboard calls the initWithCoder: method, we directly write the code in this method. Run the program to view the display on the terminal. 11:45:55. 256 LearnNSURLSession [829: 541b] {"ticker": {"buy": "4376.99", "high": "4388.02", "last": "4376.99 ", "low": "4246.0", "medium": "4377.0", "vol": "3874.2808 "}}OK. The returned data is correct. Of course, the above Code does not use NSURLSessionConfiguration to save time.
 

 

This line of code is replaced
*session = [NSURLSession sessionWithConfiguration:configuration];

 

NSURLSessionConfiguration is used in this way. Of course, other configurations are not required for this applet. However, it is necessary to introduce the three basic configurations of NSURLSessionConfiguration:
  • BackgroundSessionConfiguration: -- this allows you to download in the background and use the network push notification.
  • DefaultSessionConfiguration -- this is the default configuration. cache, cookie, and credential are used by default.
  • EphemeralSessionConfiguration -- no cache, cookie, and credential are used.

 

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.