Data receiving process for iOS network requests (nsurlrequest & nsurlconnection)

Source: Internet
Author: User

Network Programming usually goes through the request --- connection --- response (request -- connection -- Response) process.

The general steps are as follows:

1. Create an nsurl first.

2. Create an nsurlrequest using the specified URL. You can also specify the Cache Policy and timeout time.

3. Create an nsurlconnection according to your request and respond to your connection (synchronous and asynchronous ).

The process is described in detail below

1. Create a URL

    NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];

2. Create an nsurlrequest

NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

The initialization parameter initwithurl specifies the URL to be accessed, cachepolicy specifies the cache policy (including 6), and timeoutinterval specifies the timeout time.

Cache Policy:

NSURLRequestCachePolicyThese constants are used to specify interaction with the cached responses.enum{   NSURLRequestUseProtocolCachePolicy = 0,   NSURLRequestReloadIgnoringLocalCacheData = 1,   NSURLRequestReloadIgnoringLocalAndRemoteCacheData =4,   NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,   NSURLRequestReturnCacheDataElseLoad = 2,   NSURLRequestReturnCacheDataDontLoad = 3,   NSURLRequestReloadRevalidatingCacheData = 5};typedef NSUInteger NSURLRequestCachePolicy;

A little explanation:

Nsurlrequestuseprotocolcachepolicy (Basic Policy) is the Default policy of nsurlrequest.

Nsurlrequestreloadignoringlocalcachedata (ignore local cache)

Nsurlrequestreturncachedataelseload)

Nsurlrequestreturncachedatadontload)

Nsurlrequestreloadignoringlocalandremotecachedata (regardless of any cache policy, whether local or remote, it is always downloaded from the original address)

Nsurlrequestreloadrevalidatingcachedata (if the local cache is valid, it will not be downloaded. Otherwise, it will be downloaded again from the original address)

For more information, see this blog: http://blog.csdn.net/zeng11088/article/details/8544759 (

Translation of the nsurlrequest Official Document

)

3. Create nsurlconnection & Response

First, network programming has two connection modes: synchronous and asynchronous,The connection adopts synchronous response throughUse sendsynchronousrequesT method, while asynchronous responses are implemented through the nsurlconnectiondelegate method..
(1) synchronous connection response: use this method.

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request  returningResponse:(NSURLResponse **)response  error:(NSError **)error

For example:

NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];


(2) asynchronous connection response: proxy implementation

Call the following proxy methods after creating a connection:

NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

① Sent when the connection has received ed sufficient data to construct the URL response for its request.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

② Sent as a connection loads data incrementally.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

③ Sent when a connection has finished loading successfully

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

④ Sent when a connection fails to load its request successfully.

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

A slight explanation of this process: if the connection receives the response, it will call the method didreceiveresponse in delegate. here we need to create a data buffer, which is the first step. Then, a little bit of data is received and appended to the previously created data. This process will repeatedly call the didreceivedata method, which is the second step. If the acceptance is complete, the connectiondidfinishloading method is called, indicating that all data is received. If an error or exception occurs, the method didfailwitherror is called to end. This is the third step.

Note: If the program is suspended when half of the network request is sent, what should I do if the network connection is suspended? In fact, when the program exits, the system will not immediately suspend the application process, but will delay about one second. If the request is still not completed, the system will silently help you receive all the data, saves the request timeout for so long. For example, if you set a time-out period of 30 s and re-open the application within 30 s, the data will be immediately received once. If the application is not opened, sorry. The didfailwitherror method of Delegate will be called the next time you open the program, the request times out.


For more information, see the next blog.


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.