IOS development network-basic use of NSURLConnection, iosnsurlconnection

Source: Internet
Author: User

IOS development network-basic use of NSURLConnection, iosnsurlconnection

IOS development network-basic use of NSURLConnection

I. Common NSURLConnection classes

(1) NSURL: request address

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

(3) NSMutableURLRequest: NSURLRequest subclass

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

 

Ii. Use of NSURLConnection1. Simple Description

The procedure for sending a request using NSURLConnection is simple.

(1) Create an NSURL object and set the Request Path (set the Request Path)

(2) Input NSURL to create an NSURLRequest object and set the request header and request body (CREATE request object)

(3) Use NSURLConnection to send NSURLRequest (Send request)

2. Sample Code

(1) Three Steps for sending a request:

1. set Request Path 2. create a request object 3. send request 3.1 send a synchronous request (this line of code gets stuck while waiting for the server to return data. If the server does not return data, the main thread UI gets stuck and cannot continue the operation) if a return value is set to 3.2, an asynchronous request is sent. If no return value is set, all nsurlrequests are get requests by default. (2) sample code for sending a synchronization request:
1 // 2 // YYViewController. m 3 // 01-NSURLConnection usage (GET) 4 // 5 // Created by apple on 14-6-28. 6 // Copyright (c) 2014 itcase. all rights reserved. 7 // 8 9 # import "YYViewController. h "10 # import" MBProgressHUD + MJ. h "11 12 @ interface YYViewController () 13 @ property (weak, nonatomic) IBOutlet UITextField * username; 14 @ property (weak, nonatomic) IBOutlet UITextField * pwd; 15-(IBAction) login; 16 17 @ end18 19 @ implementation YYViewController20 21-(IBAction) login {22 // 1. early Form Verification 23 if (self. username. text. length = 0) {24 [MBProgressHUD showError: @ "enter username"]; 25 return; 26} 27 if (self. pwd. text. length = 0) {28 [MBProgressHUD showError: @ "Enter Password"]; 29 return; 30} 31 // 2. send a request to the server (with the account and password) 32 // Add a mask to prohibit user operation 33 // [MBProgressHUD showMessage: @ "loading .... "]; 34 // GET request: Request Line \ Request Header \ Request body 35 // 36 // 1. set Request Path 37 NS String * urlStr = [NSString stringWithFormat: @ "http: // 192.168.1.53: 8080/MJServer/login? Username = % @ & pwd = % @ ", self. username. text, self. pwd. text]; 38 NSURL * url = [NSURL URLWithString: urlStr]; 39 // 2. create a request object 40 NSURLRequest * request = [NSURLRequest requestWithURL: url]; 41 // 3. send request 42 // send a synchronous request. Execute 43 NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil] in the main thread; 44 // (this line of code gets stuck while waiting for the server to return data. If the server does not return data, the main thread UI gets stuck and cannot continue the operation) 45 NSLog (@ "-- % d --", data. length); 46} 47 @ end

Simulator status:

Print the information returned by the server:

Note: 1. advance Form Verification 2. send a request to the server (with the account and password) GET request: Request Line \ Request Header \ request Body Note: The GET request does not contain the Request body, because all the information is written in the URL. In IOS, neither the request line nor the request header needs to be written. (3) There are two methods for sending asynchronous requests: 1) using block callback 2) proxy A. Use the block callback method to send asynchronous requestsSample Code for block callback:
1 // 2 // YYViewController. m 3 // 01-NSURLConnection usage (GET) 4 // 5 // Created by apple on 14-6-28. 6 // Copyright (c) 2014 itcase. all rights reserved. 7 // 8 9 # import "YYViewController. h "10 # import" MBProgressHUD + MJ. h "11 12 @ interface YYViewController () 13 @ property (weak, nonatomic) IBOutlet UITextField * username; 14 @ property (weak, nonatomic) IBOutlet UITextField * pwd; 15-(IBAction) login; 16 17 @ end18 19 @ implementation YYViewController20 21-(IBAction) login {22 // 1. early Form Verification 23 if (self. username. text. length = 0) {24 [MBProgressHUD showError: @ "enter username"]; 25 return; 26} 27 if (self. pwd. text. length = 0) {28 [MBProgressHUD showError: @ "Enter Password"]; 29 return; 30} 31 // 2. send a request to the server (with the account and password) 32 // Add a mask to prohibit user operation 33 [MBProgressHUD showMessage: @ "loading .... "]; 34 35 // 36 // 1. set Request Path 37 NSString * urlStr = [NSStrin G stringWithFormat: @ "http: // 192.168.1.53: 8080/MJServer/login? Username = % @ & pwd = % @ ", self. username. text, self. pwd. text]; 38 NSURL * url = [NSURL URLWithString: urlStr]; 39 40 // 2. create a request object 41 NSURLRequest * request = [NSURLRequest requestWithURL: url]; 42 43 // 3. send request 44 // 3.1 send synchronous request, execute 45 // NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil] in the main thread; 46 // (this line of code gets stuck while waiting for the server to return data. If the server does not return data, the main thread UI gets stuck and cannot continue the operation) 47 48 // 3.1 send asynchronous request 49 // create a queue (tasks added to this queue are executed asynchronously by default) 50 // NSOperationQueue * queue = [[NSOperationQueue alloc] init]; 51 // obtain a main queue column 52 NSOperationQueue * queue = [NSOperationQueue mainQueue]; 53 [NSURLConnection failed: request queue: queue completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {54 NSLog (@ "-- block callback data -- % @ --- % d", [NSThread currentThread], data. length); 55 // hide the HUD. The UI refresh operation must be performed in the main thread 56 [MBProgressHUD hideHUD]; 57 58 // parse data59/* 60 {"success ": "Logon successful"} 61 {"error": "user name does not exist"} 62 {"error": "Incorrect password"} 63 */64 NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: nil]; 65 NSLog (@ "% @", dict); 66 67 // after judgment, the interface prompts logon information 68 NSString * error = dict [@ "error"]; 69 if (error) {70 [MBProgressHUD showError: error]; 71} else72 {73 NSString * success = dict [@ "success"]; 74 [MBProgressHUD showSuccess: success]; 75} 76}]; 77 NSLog (@ "request sent"); 78} 79 @ end

Simulator (note that a third-party framework is used here ):

Print and view:

Code Description: block code segment: when the server returns data, a new thread is called to send the request, and the main thread continues to go down, when the data returned by the server is obtained, the block is called back and the block code segment is executed. In this case, the main thread is not stuck. The role of the queue: determines the thread in which the block operation is executed? Operations to refresh the UI should be performed in the main thread rather than in the sub-thread. some inexplicable problems may occur when the sub-thread processes UI-related operations. Tip: (1) Create an operation and place it in the NSOperation queue for execution. The default operation is asynchronous. (2) mainqueue returns a queue related to the main thread, that is, the main queue column. New Problem: if a request is sent to the server but no data is obtained, the program will crash (data cannot be blank) to improve the Code:
1 NSOperationQueue * queue = [NSOperationQueue mainQueue]; 2 [NSURLConnection failed: request queue: queue completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {3 // call when the request ends (two results are available: data is obtained successfully or data is not obtained, and the request fails) 4 NSLog (@ "-- block callback data -- % @ --- % d", [NSThread currentThread], data. length); 5 // hide the HUD. The UI refresh operation must be performed in the main thread for 6 [MBProgressHUD hideHUD]; 7 8 // parse data 9/* 10 {"Success": "Logon successful"} 11 {"error": "user name does not exist"} 12 {"error": "Incorrect password"} 13 */14 if (data) {// request succeeded 15 NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: nil]; 16 NSLog (@ "% @", dict ); 17 18 // after judgment, the logon information 19 NSString * error = dict [@ "error"] is displayed; 20 if (error) {21 [MBProgressHUD showError: error]; 22} else23 {24 NSString * success = dict [@ "success"]; 25 [MBProgressHUD showSucces S: success]; 26} 27} else // request failed 28 {29 [MBProgressHUD showError: @ "Network busy. Please try again later! "]; 30} 31 32}];
Parse data
// Parse data/* {"success": "Logon successful"} {"error": "user name does not exist"} {"error": "Incorrect password "}*/
Note: The object returned by NSJSONSerialization depends on the outermost layer. If it is {}, It is the dictionary and [], it is the array. Note: first determine the request path, then create a request object (get request sent by default), and use an Asynchronous Method (1 call this method, it automatically starts a subthread to send a request. when the request is successful and the data is returned, the internal code segment is automatically called. The execution of this code segment in that thread depends on the queue. If it is a main queue column, after the sub-thread successfully receives the server data, it returns to the main thread to parse the data and refresh the UI ). B. Send asynchronous requests using proxy Methods

To listen to the data returned by the server, use the <NSURLConnectionDataDelegate> protocol.

Common large proxy methods are as follows:

1 # pragma mark-NSURLConnectionDataDelegate proxy method 2 3 // when a response is received from the server (connected to the server), 4 5-(void) connection (NSURLConnection *) is called *) connection didReceiveResponse :( NSURLResponse *) response 6 7 // It is called when the server receives data (may be called multiple times and only part of data is transferred each time) 8 9-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data10 11 // when the server's data is loaded, it will call 12 13-(void) connectionDidFinishLoading :( NSURLConnection *) connection14 15 // call when a request error (failure) (request timeout \ Network disconnection \ no network \, usually a client error) 16 17-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error

Sample Code for sending a get request using an Asynchronous Method:

 

1 // 2 // YYViewController. m 3 // 01-NSURLConnection usage (GET) 4 // 5 // Created by apple on 14-6-28. 6 // Copyright (c) 2014 itcase. all rights reserved. 7 // 8 9 # import "YYViewController. h "10 # import" MBProgressHUD + MJ. h "11 12 @ interface YYViewController () <NSURLConnectionDataDelegate> 13 @ property (weak, nonatomic) IBOutlet UITextField * username; 14 @ property (weak, nonatomic) IBOutlet UITextFi Eld * pwd; 15 @ property (nonatomic, strong) NSMutableData * responseData; 16-(IBAction) login; 17 18 @ end 19 20 @ implementation YYViewController 21 22-(IBAction) login {23 // 1. early Form Verification 24 if (self. username. text. length = 0) {25 [MBProgressHUD showError: @ "enter username"]; 26 return; 27} 28 if (self. pwd. text. length = 0) {29 [MBProgressHUD showError: @ "Enter Password"]; 30 return; 31} 32 // 2. send a request to the server (with the account and password) 33 // Add A mask to prohibit user operation 34 [MBProgressHUD showMessage: @ "loading .... "]; 35 36 // 37 // 2.1 set the Request Path 38 NSString * urlStr = [NSString stringWithFormat: @" http: // 192.168.1.53: 8080/MJServer/login? Username = % @ & pwd = % @ ", self. username. text, self. pwd. text]; 39 NSURL * url = [NSURL URLWithString: urlStr]; 40 41 // 2.2 create a request object 42 // NSURLRequest * request = [NSURLRequest requestWithURL: url]; // GET request 43 by default // Set request timeout 44 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; 45 request. timeoutInterval = 5.0; 46 47 // 2. 3. send request 48 // use a proxy to send an asynchronous request (usually used for file download) 49 NSURLConnection * conn = [NSURLConnection conn EctionWithRequest: request delegate: self]; 50 [conn start]; 51 NSLog (@ "sent request ---"); 52} 53 54 # pragma mark-NSURLConnectionDataDelegate proxy Method 55/* 56 * When a server response (connected to the server) is received, 57 */58-(void) is called) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response 59 {60 NSLog (@ "received Server response"); 61 // initialize data 62 self. responseData = [NSMutableData data]; 63} 64 65/* 66 * It is called when server data is received (may be called multiple times, Only part of data is transmitted each time.) 67 */68-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data 69 {70 NSLog (@ "received server data"); 71 // concatenate data 72 [self. responseData appendData: data]; 73 NSLog (@ "% d --- % @ --", self. responseData. length, [NSThread currentThread]); 74} 75 76/* 77 * when the server's data is loaded, it will call 78 */79-(void) connectionDidFinishLoading :( NSURLConnection *) connection 80 {81 NSLog (@ "server data loaded"); 82 // hide the HUD 83 [MBProgressHUD hideHUD]; 84 85 // process all data returned by the server 86 NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: self. responseData options: NSJSONReadingMutableLeaves error: nil]; 87 88 // after judgment, the system prompts the logon information 89 NSString * error = dict [@ "error"]; 90 if (error) {91 [MBProgressHUD showError: error]; 92} else 93 {94 NSString * success = dict [@ "success"]; 95 [MBProgressHUD showSuccess: success]; 96} 97 NSLog (@ "% d --- % @ -- ", Self. responseData. length, [NSThread currentThread]); 98} 99/* 100 * call when the request is incorrect (failed) (request timeout \ Network disconnection \ no network \, usually a client error) 101 */102-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error103 {104 // NSLog (@ "request error "); 105 // hide HUD106 [MBProgressHUD hideHUD]; 107 [MBProgressHUD showError: @ "the network is busy. Please try again later! "]; 108} 109 @ end

 

Print and view:

 

Supplement:

(1) Data Processing

In the didReceiveData: method, splice all received data and process it in connectionDidFinishLoading: method after all data is obtained.

(2) network latency

When developing a network, you must take into account the handling of network latency. You can set a breakpoint simulation in the server code.

Set a breakpoint in the login method of the server code

Sets the maximum latency of a request.

 

Simulator status:

Print and view:

Iii. NSMutableURLRequest

NSMutableURLRequest is a subclass of NSURLRequest. Common methods include:

Set the request timeout wait time (if this time is exceeded, the request fails)-(void) setTimeoutInterval :( NSTimeInterval) seconds;

Set the request method (such as GET and POST)-(void) setHTTPMethod :( NSString *) method;

Set the Request body-(void) setHTTPBody :( NSData *) data;

Set the request header-(void) setValue :( NSString *) value forHTTPHeaderField :( NSString *) field;

 

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.