Methods for using Nsurlconnection classes to handle network requests in IOS development _ios

Source: Internet
Author: User
Tags reserved

Nsurlconnection as an abstraction above the Core foundation/cfnetwork framework API, in 2003, as the first edition of Safari was released. Nsurlconnection this name, in effect, refers to the Foundation frame URL loading system in a series of associated components: Nsurlrequest, Nsurlresponse, Nsurlprotocol, Nsurlcache, Nshttpcookiestorage, Nsurlcredentialstorage, and class nsurlconnection with the same name.

Nsurlrequest was passed on to Nsurlconnection. A nsurlresponse is returned asynchronously by the delegate object (following the previous informal protocol <NSURLConnectionDelegate> and <NSURLConnectionDataDelegate>) And nsdata that contains server return information.

Before a request is sent to the server, the system queries the shared cache information and then, depending on the policy (policy) and availability (availability), a response that has already been cached may be returned immediately. If no cached response is available, the request caches its response based on the policy we specify so that future requests can be used.

In the process of sending a request to the server, the server may issue a authentication query (authentication challenge), which can be automatically responded by a shared cookie or a secret store (credential storage), or by a delegate object. Requests in the send can also be intercepted by registered Nsurlprotocol objects to seamlessly change their loading behavior when necessary.

In any case, nsurlconnection, as a network infrastructure, has already serviced thousands of IOS and Mac OS apps and is doing pretty well. But over the years, some use cases--especially on the IPhone and the IPad--have challenged several of Nsurlconnection's core concepts, giving Apple reason to refactor it.

First, the Nsurlconnection common class

(1) Nsurl: Request Address

(2) Nsurlrequest: Encapsulates a request to save all data to the server, including a Nsurl object, request method, request header, request body ....

(3) Subclasses of Nsmutableurlrequest:nsurlrequest

(4) Nsurlconnection: Responsible for sending requests, establishing a connection between the client and the server. Send nsurlrequest data to the server and collect response data from the server

Second, the use of nsurlconnection
1. Simple description
The steps to send a request using Nsurlconnection are simple

(1) Create a Nsurl object, set the request path (set request path)

(2) Incoming Nsurl creates a Nsurlrequest object, sets the request header and the request body (creates the request object)

(3) Use Nsurlconnection to send nsurlrequest (send request)

2. code example

(1) Three steps to send a request:

1. Set the request path
2. Create the Request object
3. Send Request
3.1 Send a sync request (has been waiting for the server to return data, this line of code will be stuck, if the server, no return data, then the main thread UI will be stuck can not continue to perform operation) has a return value
3.2 Send asynchronous Request: no return value
Description: Any nsurlrequest default is a GET request.

(2) Send synchronous request code sample:

Copy Code code as follows:

//
Yyviewcontroller.m
Use of 01-nsurlconnection (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


Copy Code code as follows:

@implementation Yyviewcontroller

-(ibaction) Login {
1. Pre-form validation
if (self.username.text.length==0) {
[Mbprogresshud showerror:@ "Please enter user name"];
Return
}
if (self.pwd.text.length==0) {
[Mbprogresshud showerror:@ "Please enter the password"];
Return
}
2. Send the request to the server (with account number and password)
Add a mask to prevent user action
[Mbprogresshud showmessage:@ "is 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=%@", Self.username.text,self.pwd.text];
Nsurl *url=[nsurl URLWITHSTRING:URLSTR];
2. Create the Request object
Nsurlrequest *request=[nsurlrequest Requestwithurl:url];
3. Send Request
Send sync request, execute on main thread
NSData *data=[nsurlconnection sendsynchronousrequest:request Returningresponse:nil Error:nil];
(Always 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 can not continue to perform operations)
NSLog (@ "--%d--", data.length);
}
@end


Simulator Condition:

Information returned by the print server:

Supplementary Note:
1. Pre-form validation
2. Send the request to the server (with account number and password)
GET request: Request line \ request header \ Request Body
Note: The request body is not present in the GET request because all the information is written in the URL. In iOS, request lines and request headers are not written.

(3) Send asynchronous request
There are two ways to send an asynchronous request:
1) using block callback
2) Agent
A. Sending an asynchronous request using the block callback method
Use the block callback code example:

Copy Code code as follows:

//
Yyviewcontroller.m
Use of 01-nsurlconnection (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


Copy Code code as follows:

@implementation Yyviewcontroller

-(ibaction) Login {
1. Pre-form validation
if (self.username.text.length==0) {
[Mbprogresshud showerror:@ "Please enter user name"];
Return
}
if (self.pwd.text.length==0) {
[Mbprogresshud showerror:@ "Please enter the password"];
Return
}
2. Send the request to the server (with account number and password)
Add a mask to prevent user action
[Mbprogresshud showmessage:@ "is trying to load ..."];

//
1. Set the request path
NSString *urlstr=[nsstring stringwithformat:@ "http://192.168.1.53:8080/mjserver/login?username=%@&pwd=%@", Self.username.text,self.pwd.text];
Nsurl *url=[nsurl URLWITHSTRING:URLSTR];

2. Create the Request object
Nsurlrequest *request=[nsurlrequest Requestwithurl:url];

3. Send Request
3.1 Send sync request, execute in main thread
NSData *data=[nsurlconnection sendsynchronousrequest:request Returningresponse:nil Error:nil];
(Always 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 can not continue to perform operations)

3.1 Sending an asynchronous request
Create a queue (tasks that are added by default to this queue are executed asynchronously)
Nsoperationqueue *queue=[[nsoperationqueue Alloc]init];
Get a Home team column
Nsoperationqueue *queue=[nsoperationqueue Mainqueue];
[Nsurlconnection sendasynchronousrequest:request queue:queue completionhandler:^ (NSURLResponse *response, NSData * Data, Nserror *connectionerror) {
NSLog (@ "--block callback data--%@---%d", [Nsthread currentthread],data.length);
Hide HUD, the operation of refreshing the UI must be placed in the main thread execution
[Mbprogresshud Hidehud];

Parsing data
/*
{"Success": "Login Succeeded"}
{"Error": "User name does not exist"}
{"Error": "Incorrect Password"}
*/
Nsdictionary *dict=[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves Error:nil];
NSLog (@ "%@", dict);

After judging, the interface prompts for login information
NSString *error=dict[@ "Error"];
if (Error) {
[Mbprogresshud Showerror:error];
}else
{
NSString *success=dict[@ "Success"];
[Mbprogresshud showsuccess:success];
}
}];
NSLog (@ "Send request completed");
}
@end


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

Print View:

Code Description:
Block Code snippet: When the server has to return data when the call will open a new thread to send the request, the main thread continues to go down, when the data returned to the server back to block, execution block code snippet. This situation does not get stuck to the main thread.
The role of the queue: decide which thread the block operation is to execute?
The actions to refresh the UI interface should be placed in the main thread execution, not on the child thread, and there are some inexplicable problems with the child threading UI-related operations.
Tips:
(1) Create an operation to be executed in the Nsoperation queue, which is executed asynchronously by default.
(2) Mainqueue returns a queue related to the main thread, that is, the home team column.

New question: If you send a request to the server but don't get the data, the program crashes (data cannot be empty)
Improved code:

Copy Code code as follows:

Nsoperationqueue *queue=[nsoperationqueue Mainqueue];
[Nsurlconnection sendasynchronousrequest:request queue:queue completionhandler:^ (NSURLResponse *response, NSData * Data, Nserror *connectionerror) {
Call at the end of the request (there are two results, one is the success of the data, may not get the data, the request failed)
NSLog (@ "--block callback data--%@---%d", [Nsthread currentthread],data.length);
Hide HUD, the operation of refreshing the UI must be placed in the main thread execution
[Mbprogresshud Hidehud];

Parsing data
/*
{"Success": "Login Succeeded"}
{"Error": "User name does not exist"}
{"Error": "Incorrect Password"}
*/
if (data) {//Request succeeded
Nsdictionary *dict=[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves Error:nil];
NSLog (@ "%@", dict);

After judging, the interface prompts for login information
NSString *error=dict[@ "Error"];
if (Error) {
[Mbprogresshud Showerror:error];
}else
{
NSString *success=dict[@ "Success"];
[Mbprogresshud showsuccess:success];
}
}else//Request failed
{
[Mbprogresshud showerror:@ network Busy, please try again later!) "];
}

}];

Parsing data
Copy Code code as follows:

Parsing data
/*
{"Success": "Login Succeeded"}
{"Error": "User name does not exist"}
{"Error": "Incorrect Password"}
*/

Description: The object returned using nsjsonserialization depends on what the outermost layer is, if it is {} that is the dictionary, [] that is the array.
Supplementary Note:
First determine the request path, it then creates the Request object (the default send-time GET request), uses the asynchronous method (a call to this method, it automatically opens a child thread to send the request, when the request succeeds, the data returns automatically calls the internal code snippet, the code snippet executes on that thread depending on the queue, If it is the home row, then after the child thread sends the request successfully to the server's data, return to the main thread to parse the data and refresh the UI interface.

B. Sending an asynchronous request using the Proxy method
To listen for data returned by the server, use the <NSURLConnectionDataDelegate> protocol

Common large agent methods are as follows:

Copy Code code as follows:

#pragma mark-nsurlconnectiondatadelegate Proxy method

Called when a response to the server (connected to the server) is received

-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response

Called when the server's data is received (it may be invoked multiple times, passing only part of the data at a time)

-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data

Called when the server's data is loaded

-(void) connectiondidfinishloading: (nsurlconnection *) connection

Call (Request timeout \ Disconnected network \ No network \, generally refers to client error) when request error (failure)

-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error


code example to send a GET request using an asynchronous method:
Copy Code code as follows:

//
Yyviewcontroller.m
Use of 01-nsurlconnection (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


Copy Code code as follows:

@implementation Yyviewcontroller

-(ibaction) Login {
//    1. Advanced form Validation
    if (self.username.text.length==0) {
        [Mbprogresshud showerror:@ "Please enter user name"];
        return;
   }
    if (self.pwd.text.length==0) {
        [Mbprogresshud showerror:@ "Please enter the password"];
        return;
   }
//    2. Send a request to the server (with account and password)
   //Add a mask to prevent user actions
    [ Mbprogresshud showmessage:@ "is trying to load ..."];

//
//   2.1 Set request path
    nsstring *urlstr=[nsstring stringwithformat:@ "http:// 192.168.1.53:8080/mjserver/login?username=%@&pwd=%@ ", Self.username.text,self.pwd.text];
    nsurl *url=[nsurl urlwithstring:urlstr];
   
//   2.2 Create the Request object
//    nsurlrequest *request=[nsurlrequest requestwithurl:url];//default is GET request
   //Set Request Timeout
    nsmutableurlrequest *request =[nsmutableurlrequest  Requestwithurl:url];
    request.timeoutinterval=5.0;
   
//   2.3. Send request
 //use proxy to send asynchronous requests (typically for file downloads)
    Nsurlconnection *conn=[nsurlconnection connectionwithrequest:request delegate:self];
    [conn start];
    NSLog (@ "has issued a request---");
}

#pragma mark-nsurlconnectiondatadelegate Proxy method
/*
* Called when a response to the server (connected to the server) is received
*/
-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response
{
NSLog (@ "Receive server response");
Initializing data
Self.responsedata=[nsmutabledata data];
}

/*
* Called when receiving data from the server (may be called multiple times, only partial data is passed at a time)
*/
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data
{
NSLog (@ "Data received from server");
Stitching data
[Self.responsedata Appenddata:data];
NSLog (@ "%d---%@--", self.responsedata.length,[nsthread CurrentThread]);
}

/*
* When the server's data is loaded, it is called
*/
-(void) connectiondidfinishloading: (nsurlconnection *) connection
{
NSLog (@ "Server data loading complete");
Hide HUD
[Mbprogresshud Hidehud];

Processing all data returned by the server
Nsdictionary *dict=[nsjsonserialization JSONObjectWithData:self.responseData options:nsjsonreadingmutableleaves Error:nil];

After judging, the interface prompts for login information
NSString *error=dict[@ "Error"];
if (Error) {
[Mbprogresshud Showerror:error];
}else
{
NSString *success=dict[@ "Success"];
[Mbprogresshud showsuccess:success];
}
NSLog (@ "%d---%@--", self.responsedata.length,[nsthread CurrentThread]);
}
/*
* Request error (failure) when called (Request timeout \ Disconnected network \ No network \, generally refers to client error)
*/
-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error
{
NSLog (@ "request Error");
Hide HUD
[Mbprogresshud Hidehud];
[Mbprogresshud showerror:@ network Busy, please try again later!) "];
}
@end


Print View:

Add:

(1) Processing of data

In the Didreceivedata: method, the concatenation of all the data received, and so on, after all the data has been received, in the connectiondidfinishloading: Method of processing

(2) Network latency

When doing the network development, must consider the network delay situation processing, can set a breakpoint simulation in the server code.

To set a breakpoint in the login method of the server code

Set maximum latency for a request

Simulator Condition:

Print View:

Third, Nsmutableurlrequest

Nsmutableurlrequest is a subclass of Nsurlrequest, and the common methods are

Set Request Timeout wait time (even if timeout is exceeded, request fails)

Copy Code code as follows:
-(void) Settimeoutinterval: (nstimeinterval) seconds;

Set request methods (such as Get and post)

Copy Code code as follows:
-(void) Sethttpmethod: (NSString *) method;

Set up the request body

Copy Code code as follows:
-(void) Sethttpbody: (NSData *) data;

Set Request headers

Copy Code code as follows:
-(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.