IOS Development Network – Basic use of NSURLConnection

NSURLConnection class

(1) NSURL: request address

(2) NSURLRequest: encapsulates a request and saves all the data sent to the server, including an NSURL object, request method, request header and request body….

(3) NSMutableURLRequest: subclass of NSURLRequest

(4) NSURLConnection: responsible for sending requests and establishing the connection between the client and server. Send the NSURLRequest data to the server and collect the response data from the server

As a developer, it’s especially important to have a learning atmosphere and a networking community, and this is one of my iOS networking groups:812157648, no matter you are small white or big ox welcome to enter, share BAT, Ali interview questions, interview experience, discuss technology, we exchange learning growth together!

Second, the use of NSURLConnection

1. The procedure for sending a request using NSURLConnection is simple

(1) create a NSURL object, set request path (set request path)

(2) Create a NSURLRequest object, set the request header and request body (create request object)

(3) Use NSURLConnection to send NSURLRequest

2. Code examples

(1) Three steps to send a request:

1. Set a request path

2. Create a request object

3. Send the request

3.1 Sending a synchronous request (waiting for the server to return data, this line of code will be stuck, if the server does not return data, then the main thread UI will be stuck and cannot continue to perform the operation) has a return value

3.2 Sending an Asynchronous Request: No Return Value Description: Any NSURLRequest is a GET request by default.

(2) send synchronous request code example:

// // yyViewController. m // 01-NSURLConnection usage (GET) // // Created by Apple on 14-6-28. // Copyright (c) 2014 ITCase.  All rights reserved. // #import "YYViewController.h" #import "MBProgressHUD+MJ.h" @interface YYViewController () @property (weak, nonatomic) IBOutlet UITextField *username; @property (weak, nonatomic) IBOutlet UITextField *pwd; - (IBAction)login; @end @implementation YYViewController - (IBAction)login { // 1. Early form validation if (self. Username. Text. Length = = 0) {[MBProgressHUD showError: @ "please enter the user name"]. return; } if (self.pwd.text.length==0) {MBProgressHUD showError:@" please enter password "]; return; // [MBProgressHUD showMessage:@" trying to load...."] ; // GET request: Request line/Request Header/request body // // 1. Set the request path NSString *urlStr=[NSString StringWithFormat: @ "http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@", the self. The username. The text, the self. PWD. Text]; NSURL *url=[NSURL URLWithString:urlStr]; NSURLRequest *request=[NSURLRequest requestWithURL:url]; / / 3. Send the request / / send a synchronous request, in the main thread to perform NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];  NSLog(@"--%d--",data.length); NSLog(@"--%d--",data.length); } @endCopy the code

Simulator situation:

Print the message returned by the server:

Supplementary notes:

1. Advance form validation

2. Send the request to the server (with the account and password). GET request: request line, request header, request body Note: There is no request body in the GET request because all the information is written in the URL. In IOS, neither the request line nor the request header is written.

There are two ways to send an asynchronous request:

1) Use block callback

2) agent

A. Use the block callback method to send an asynchronous request examples of code using the block callback method:

// // yyViewController. m // 01-NSURLConnection usage (GET) // // Created by Apple on 14-6-28. // Copyright (c) 2014 ITCase.  All rights reserved. // #import "YYViewController.h" #import "MBProgressHUD+MJ.h" @interface YYViewController () @property (weak, nonatomic) IBOutlet UITextField *username; @property (weak, nonatomic) IBOutlet UITextField *pwd; - (IBAction)login; @end @implementation YYViewController - (IBAction)login { // 1. Early form validation if (self. Username. Text. Length = = 0) {[MBProgressHUD showError: @ "please enter the user name"]. return; } if (self.pwd.text.length==0) {MBProgressHUD showError:@" please enter password "]; return; [MBProgressHUD showMessage:@" trying to load...."] ; // // 1. Set the request path NSString *urlStr=[NSString StringWithFormat: @ "http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@", the self. The username. The text, the self. PWD. Text]; NSURL *url=[NSURL URLWithString:urlStr]; NSURLRequest *request=[NSURLRequest requestWithURL:url]; 3.1 Sending a synchronization request, In the implementation of the main thread / / NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil]; // This line of code is stuck waiting for the server to return data. If the server does not return data, NSOperationQueue *queue=[[NSOperationQueue alloc]init]; NSOperationQueue *queue=[NSOperationQueue alloc]init]; NSOperationQueue *queue=[NSOperationQueue mainQueue]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {NSLog(@"--block callback --%@-- %d", [NSThread currentThread],data.length); [MBProgressHUD hideHUD]; // data /* {"success":" login succeeded "} {"error":" user name not found "} {"error":" password incorrect "} */ NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"%@",dict); NSString *error=dict[@"error"]; if (error) {[MBProgressHUD showError:error]; NSString *error=dict[@"error"];  }else { NSString *success=dict[@"success"]; [MBProgressHUD showSuccess:success]; } }]; NSLog(@" request completed "); } @endCopy the code

Emulator situation (note the use of third-party frameworks) :

Print to view:

Code description:

Block: when the server returns data, the call will open a new thread to send the request, the main thread continues, when the server returns data to call back the block, execute the block. This does not block the main thread.

The queue is used to determine which thread will execute the block operation.

The operation of refreshing THE UI interface should be carried out in the main thread, not in the child thread, which may cause some inexplicable problems in processing UI-related operations.

Tip:

(1) Create an operation and place it in the NSOperation queue. The default operation is asynchronous.

(2) MainQueue returns a queue associated with the main thread.

New problem: if you send a request to the server and don’t get data, the application will crash (data can’t be empty)

NSOperationQueue *queue=[NSOperationQueue mainQueue]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {// Called when the request ends. Request failed) NSLog(@"--block callback data --%@-- %d", [NSThread currentThread],data.length); [MBProgressHUD hideHUD]; Analytical data / / / * {" success ", "login succeeds"} {" error ":" the user name does not exist "} {" error ":" password incorrect "} * / if (data) {/ / request NSDictionary success *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"%@",dict); NSString *error=dict[@"error"]; if (error) {[MBProgressHUD showError:error]; NSString *error=dict[@"error"];  }else { NSString *success=dict[@"success"]; [MBProgressHUD showSuccess:success]; }}else {[MBProgressHUD showError:@" Network busy, please try again later! "];}}];Copy the code

Analytical data

Analytical data / / / * {" success ", "login succeeds"} {" error ":" the user name does not exist "} {" error ":" password incorrect "} * /Copy the code

NSJSONSerialization returns an object, depending on the outermost layer. {} is a dictionary, [] is an array, etc.

Supplementary notes:

First determine the request path, and then create the request object (the default send a get request), use the asynchronous method (a call to this method, it will automatically open a child thread to send the request, when the request is successful, the data returned automatically calls the internal code, the code segment in the thread execution depends on the queue, if it is the home team, After the child thread sends the request successfully to get the data from the server, it returns to the main thread to parse the data and refresh the UI interface.

B. Use a proxy method to send an asynchronous request

Common large proxy methods are as follows:

# pragma mark - NSURLConnectionDataDelegate agent method / / when to receive the server's response (connecting the server) will call - (void) connection: the connection NSURLConnection *) DidReceiveResponse :(NSURLResponse *)response // called when data is received from the server (may be called multiple times, Only part of the data is passed ata time.) -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data // this call is called when the server data is loaded - (void) the connectionDidFinishLoading: (connection NSURLConnection *) / / request error (failure) calls (request timeout \ \ \, no net without Internet Client error) -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)errorCopy the code

Examples of code for sending a GET request using an asynchronous method:

// // yyViewController. m // 01-NSURLConnection usage (GET) // // Created by Apple on 14-6-28. // Copyright (c) 2014 ITCase.  All rights reserved. // #import "YYViewController.h" #import "MBProgressHUD+MJ.h" @interface YYViewController ()<NSURLConnectionDataDelegate> @property (weak, nonatomic) IBOutlet UITextField *username; @property (weak, nonatomic) IBOutlet UITextField *pwd; @property(nonatomic,strong)NSMutableData *responseData; - (IBAction)login; @end @implementation YYViewController - (IBAction)login { // 1. Early form validation if (self. Username. Text. Length = = 0) {[MBProgressHUD showError: @ "please enter the user name"]. return; } if (self.pwd.text.length==0) {MBProgressHUD showError:@" please enter password "]; return; [MBProgressHUD showMessage:@" trying to load...."] ; // // 2.1 Setting the request path NSString *urlStr=[NSString StringWithFormat: @ "http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@", the self. The username. The text, the self. PWD. Text]; NSURL *url=[NSURL URLWithString:urlStr]; NSURLRequest *request=[NSURLRequest requestWithURL:url]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; Request. TimeoutInterval = 5.0; / / 2.3. Send the request / / use the proxy to send asynchronous requests (usually applied to the file download) NSURLConnection * conn = [NSURLConnection connectionWithRequest: request the delegate: self].  [conn start]; NSLog(@" request made --"); } # pragma mark - NSURLConnectionDataDelegate proxy method / * * when to receive the server's response (connecting the server) will call * / - (void) connection: (NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {NSLog(@" received response from server "); Self. responseData=[NSMutableData data]; } /* * called when data is received from the server (which may be called multiple times, ) */ -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {NSLog(@" received data from the server "); [self.responseData appendData:data]; NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]); } / * * when server data to load is called * / - (void) the connectionDidFinishLoading: (connection NSURLConnection *) {NSLog (@ "at the end of server load data"); // hideHUD [MBProgressHUD hideHUD]; / / handles all the data returned from the server NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: self. The responseData options:NSJSONReadingMutableLeaves error:nil]; NSString *error=dict[@"error"]; NSString *error=dict[@"error"]; if (error) { [MBProgressHUD showError:error]; }else { NSString *success=dict[@"success"]; [MBProgressHUD showSuccess:success]; } NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]); } /* * call when request error (failed) (request timeout, disconnected, no network, ) */ -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {// NSLog(@" request error "); // hideHUD [MBProgressHUD hideHUD]; [MBProgressHUD showError:@" Network busy, please try again later! "] ; } @endCopy the code

Print to view:

Supplement:

(1) data processing in didReceiveData: method, joining together to receive all of the data, such as, after all the data to get in the connectionDidFinishLoading: method for processing

(2) network delay when doing network development, we must take into account the processing of network delay. We can set up a breakpoint simulation in the server code. Set breakpoints in the login method of the server code

Sets the maximum delay for requests

Simulator situation:

Print to view:

Third, NSMutableURLRequest

NSMutableURLRequest is a subclass of NSURLRequest

– (void)setTimeoutInterval (NSTimeInterval)seconds; – (void)setTimeoutInterval (NSTimeInterval)seconds;

Set request methods (like GET and POST) – (void)setHTTPMethod:(NSString *)method;

Set request body – (void)setHTTPBody:(NSData *)data;

– (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;

The flower field is half an mu

The original address: www.cnblogs.com/wendingding…