IOS -- NNSURLSessionDataTask, nsurlsessiondatatask

Source: Internet
Author: User
Tags tmp file

IOS -- NNSURLSessionDataTask, nsurlsessiondatatask
I. Basic Introduction

1. NSURLSessionDataTask is a subclass of NSURLSessionTask and a specific network request (task) class. It is one of the most common requests in network requests.

Generally, NSURLSessionDataTask is used to request data and download data resources, such as JSON data and image data.

 

2. There are usually the following methods to create a data task:

1) Method 1: Use the NSURLSession instance method

 

1 // @ param url the URL to be requested 2 // @ param completionHandler callback method 3 // @ param data the data requested by the server 4 // @ param response header information 5 // @ param error message 6-(NSURLSessionDataTask *) dataTaskWithURL :( NSURL *) url completionHandler :( void (^) (NSData * _ Nullable data, NSURLResponse * _ Nullable response, NSError * _ Nullable error) completionHandler;

 

Note:

In this method, the url is automatically converted to a request object (NSURLRequest), and the request object is a GET request method.

The callback method is run in the Child thread. Therefore, if you refresh the UI in the callback method, you must return to the main thread.

The callback method has two parameters: response/error. The two parameters are the same as the response/error in the Message Receiver (that is, the NSURLSessionDataTask object), that is, the address is the same.

The disadvantage of using this method is that you cannot monitor the progress of data retrieval, because this method is called only after all the data is requested. That is to say, the data in data is all the data requested.

 

2) Method 2: Use the NSURLSession instance method

 

// @ Param request object-(NSURLSessionDataTask *) dataTaskWithRequest :( NSURLRequest *) request completionHandler :( void (^) (NSData * _ Nullable data, NSURLResponse * _ Nullable response, NSError * _ Nullable error) completionHandler;

 

Method 2 differs from method 1 in that method 2 can manually set the request object so that one of the request methods can be specified in GET/POST. method 1 can only be a GET request method.

The rest are all the same

 

3) method 3: proxy

Method 1 and method 2 The only drawback is that the request progress cannot be monitored, because the callback method is called only when the request has full data. To monitor the request progress, you must use the proxy method.

To use a proxy, you must first define the NSURLSession object. You can use the following method to set the proxy object.

 

// @ Param configuration information object // @ param delegate proxy object // the thread in which the @ param queue proxy method runs, if nil is passed, the proxy method + (NSURLSession *) sessionWithConfiguration :( NSURLSessionConfiguration *) configuration delegate :( nullable id <strong>) delegate principal :( nullable NSOperationQueue;

 

At the same time, the relevant agreement must be observed.

 

Use the following method to create a data task

- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url;- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;

The difference between the two methods is the same as that between method 1 and method 2. Using a url, the method automatically converts it into a request object and is a GET request method.

 

Ii. Sample Code

Because I write all the code to a demo, I don't need to worry about anything that I don't need at the moment.

1) GET/POST requests

First, drag a UINavigationController in main. storyboard and set static cell,

 

Drag a UIViewController and select the first cell, that is, NSURLSessionDataTask. Connect the cell and UIViewController, and select push.

Drag a series of controls into the UIViewController,

 

The UIBarButtonItem in the upper-right corner jumps to the next interface.

The code in UIViewController is as follows:

 

1 # import "LHDataTaskViewController. h "2 3 // GET request URL 4 static NSString * imageURL = @" http: // 120.25.226.186: 32812/resources/images/minion_01.png "; 5 6 // POST request URL 7 static NSString * dataURL = @ "http://api.hudong.com/iphonexml.do"; 8 9 @ interface LHDataTaskViewController () 10 11 # pragma mark-attribute 12 @ property (weak, nonatomic) IBOutlet UIImageView * showImageView; 13 14 @ property (nonatomic, strong) NSURLSession * session; 15 @ property (nonatomic, strong) NSURLSessionDataTask * dataTask; 16 17 @ end18 19 @ implementation LHDataTaskViewController20 21 # pragma mark-ViewController lifecycle 22-(void) viewDidLoad {23 24 [super viewDidLoad]; 25 26 // 1. initialize NSURLSession object 27 self. session = [NSURLSession sharedSession]; 28 29} 30 31-(void) didReceiveMemoryWarning {32 33 [super didReceiveMemoryWarning]; 34 35}

 

 

1. GET request

Set the action of the "GET request" button

 

1 # pragma mark-button action method 2 # pragma mark sends a GET request to GET image resources 3-(IBAction) GETButtonClick :( id) sender {4 5 NSLog (@ "dataTask status --- % li", _ dataTask. state); 6 7 // 1. initialize NSURLSesionDataTask object 8 self. dataTask = [_ session dataTaskWithURL: [NSURL URLWithString: imageURL] completionHandler: ^ (NSData * _ Nullable data, NSURLResponse * _ Nullable response, NSError * _ Nullable error) {9 10 // 1 ). define the UIImage object and use the accepted data to initialize 11 UIImage * image = [UIImage imageWithData: data]; 12 13 // 2 ). refresh UI14 dispatch_async (dispatch_get_main_queue (), ^ {15 16 self. showImageView. image = image; 17 18}); 19 20 NSLog (@ "dataTask status --- % li", _ dataTask. state); 21 22 // at this time, all data has been accepted, so the accepted data is equal to the total data to be accepted 23 // because no data is sent, therefore, all sent data is 024 NSLog (@ "received data volume --- % lli", _ dataTask. countOfBytesReceived); // 4834725 NSLog (@ "total amount of data to be received --- % lli", _ dataTask. countOfBytesExpectedToReceive); // 4834726 NSLog (@ "sent data volume --- % lli", _ dataTask. countOfBytesSent); // 027 NSLog (@ "total amount of data to be sent --- % lli", _ dataTask. countOfBytesExpectedToSend); // 028 29}]; 30 31 // 2. send the request and execute task32 [_ dataTask resume]; 33 34}

 

Among them, the attributes used in 24 rows -- 27 rows have been described in the previous section.

Note: all tasks in NSURLSessionTask must start with resume.

 

 

2. POST request

Set the action of the "POST request" button

 

1-(IBAction) POSTButtonClick :( UIButton *) sender {2 3 // 1. create a request object (variable) 4 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: dataURL]; 5 6 // 2. set request method to post request 7 request. HTTPMethod = @ "POST"; 8 9 request. HTTPBody = [@ "type = focus-c" dataUsingEncoding: NSUTF8StringEncoding]; 10 11 // 1. initialize NSURLSessionDataTask object 12 self. dataTask = [_ session dataTaskWithRequest: request completionHandler: ^ (NSData * _ Nullable data, NSURLResponse * _ Nullable response, NSError * _ Nullable error) {13 14 NSLog (@ "% @", [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]); 15 16}]; 17 18 [_ dataTask resume]; 19 20}

 

2. Proxy

Use a proxy to perform network requests and monitor the request progress.

Drag a UIViewController In the mian. storyboard and add the control,

 

This request is an image data. After the request is complete, the image is displayed in the UIImageView on the screen. The resume button is the start request, the pause button is the pause request, and the cance button is the cancel request, there is also a UIProgressView in the middle to display the request progress and associate these controls with the outlet Variables

 

The code in UIViewController is as follows. This ViewController must comply with the relevant protocol <NSURLSessionDataDelegate>

 

1 # import "LHDataTaskDownloadViewController. h "2 3 // URL to be accessed 4 static NSString * imageURL = @" http://f12.topit.me/o129/10129120625790e866.jpg "; 5 6 @ interface LHDataTaskDownloadViewController () <NSURLSessionDataDelegate> 7 8 # pragma mark-attribute list 9 # pragma mark socket variable 10 @ property (weak, nonatomic) IBOutlet UIImageView * showImageView; 11 @ property (weak, nonatomic) IBOutlet progress * progressView; 12 @ property (weak, nonatomic) IBOutlet UIButton * handle; 13 @ property (weak, nonatomic) IBOutlet UIButton * pauseButton; 14 @ property (weak, nonatomic) IBOutlet UIButton * cancelButton; 15 16 # pragma mark network object 17 @ property (nonatomic, strong) NSURLSession * session; 18 @ property (nonatomic, strong) NSURLSessionDataTask * dataTask; 19 20 # pragma mark object 21 @ property (nonatomic, strong) NSMutableData * data; 22 23 @ end24 25 @ implementation LHDataTaskDownloadViewController26 27-(void) viewDidLoad {28 29 [super viewDidLoad]; 30 31 // 1. initialize the NSURLSession object. delegateQueue is the thread for running the Protocol method. If nil is passed, 32 self is run in the Child thread. session = [NSURLSession sessionWithConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration] delegate: self delegateQueue: nil]; 33 34 // 2. initialize the NSURLSessionDataTask object. The default value is GET35 self. dataTask = [_ session dataTaskWithURL: [NSURL URLWithString: imageURL]; 36 37 // 2. set cancelButton and pauseButton to unavailable 38 _ cancelButton. enabled = NO; 39 40 _ pauseButton. enabled = NO; 41 42}

 

 

Start button action

1-(IBAction) resumeButtonClick :( id) sender {2 3 // 1. determines the current status. data task is paused by default. 4 if (_ dataTask. state = nsurlsessiontaskstatesu0000ded) {5 6 _ pauseButton. enabled = YES; 7 8 _ cancelButton. enabled = YES; 9 10 // 1 ). start to request task11 [_ dataTask resume]; 12 13} 14 15}

 

How to pause a button

1-(IBAction) pauseButtonClick :( id) sender {2 3 // 1. determines the current status of the task. if the task is in the status of accepting data, the 4 if (_ dataTask. state = NSURLSessionTaskStateRunning) {5 6 [_ dataTask suspend]; 7 8} 9 10}

 

How to cancel a button

1-(IBAction) cancelButtonClick :( id) sender {2 3 // 1. determines the current status of the task. if the task is in the status of accepting data or paused, the 4 if (_ dataTask. state = NSURLSessionTaskStateRunning | _ dataTask. state = nsurlsessiontaskstatesu0000ded) {5 6 // 1 ). cancel task 7 [_ dataTask cancel]; 8 9 // 2 ). set the value of the slider to 10_progressview. progress = 0; 11 12 // 3 ). create dialog box VC13 UIAlertController * alertVC = [UIAlertController alertControllerWithTitle: @ "message: @" this Task has been canceled "preferredStyle: UIAlertControllerStyleAlert]; 14 15/4 ). show the dialog box VC16 [self presentViewController: alertVC animated: YES completion: nil]; 17 18 // 5 ). create action button 19 UIAlertAction * cancelAction = [UIAlertAction actionWithTitle: @ "cancel" style: UIAlertActionStyleCancel handler: ^ (UIAlertAction * _ Nonnull action) {20 21 [self. navigationController popViewControllerAnimated: YES]; 22 23}]; 24 25 // 6 ). add the action button to the dialog box VC26 [alertVC addAction: cancelAction]; 27 28} 29 30}

 

Protocol Method

# The pragma mark is called when it receives the server response. Data is not accepted by default, therefore, you must permit the // @ param session current session object // @ param dataTask current data task object // @ param response header object // @ param completionHandler callback-(void) URLSession :( NSURLSession *) session dataTask :( NSURLSessionDataTask *) dataTask complete :( NSURLResponse *) response completionHandler :( void (^) (response) completionHandler {NSLog (@ "% @", NSStringFromSelector (_ cmd); // 1. initialize the Data Object self. data = [[NSMutableData alloc] init]; // 2. accept data. If this sentence is not written, the following proxy method will not be executed completionHandler (NSURLSessionResponseAllow );}

Where NSURLSessionResponseDisposition is an enumeration

1 typedef NS_ENUM (NSInteger, NSURLSessionResponseDisposition) {2 NSURLSessionResponseCancel = 0, // cancel receiving data. The subsequent proxy method will not be executed, which is equivalent to [task cancel]; 3 NSURLSessionResponseAllow =, // accept data is allowed, and the subsequent proxy method will be executed 4 NSURLSessionResponseBecomeDownload = 2, // change the current data task to download task. When it is converted to download task, the data will be downloaded to the tmp file, no need to accept the data, and the following iii) method must be called, and nothing can be written in this method, but it must be called 5 bytes NS_ENUM_AVAILABLE (10_11, 9_0) = 3, // change the current data task to stream task6} NS_ENUM_AVAILABLE (NSURLSESSION_AVAILABLE, 7_0 );

 

1 # When pragma mark receives data, it may call 2-(void) URLSession :( NSURLSession *) session dataTask :( NSURLSessionDataTask *) dataTask didReceiveData :( NSData *) data {3 4 NSLog (@ "% @", NSStringFromSelector (_ cmd); 5 6 // 1. splicing received data 7 [self. data appendData: data]; 8 9 // 2. return to the main thread to refresh UI10 dispatch_async (dispatch_get_main_queue (), ^ {11 12 _ progressView. progress = (float) _ dataTask. countOfBytesReceived/_ dataTask. countOfBytesExpectedToReceive; 13 14}); 15 16}

 

1 # Call 2-(void) URLSession (NSURLSession *) session task (NSURLSessionTask *) task didCompleteWithError :( NSError *) When The pragma mark request ends or fails *) error {3 4 NSLog (@ "% @", NSStringFromSelector (_ cmd); 5 6 UIImage * image = [UIImage imageWithData: _ data]; 7 8 dispatch_async (dispatch_get_main_queue (), ^ {9 10 NSLog (@ "currentThread --- % @", [NSThread currentThread]); 11 12 self. showImageView. image = image; 13 14}); 15 16}

This method is not in the NSURLSessionTaskDelegate Protocol and is suitable for all tasks.

 

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.