iOS network: Nsurlconnection for asynchronous requests

Source: Internet
Author: User

Introduction: IOS applications, generally need to interact with the data through the network, so that your application becomes an online application.

The IOS SDK allows us to send requests to the network, and it's easy to get and send data through the Nsurlconnection class, and we can serialize and deserialize JSON through Nsjsonserialization. Parsing of XML uses the Nsxmlparser class. Twitter can be connected via the Twitter framework.

 

An asynchronous download via Nsurlconnection

The 1.NSURLConnection provides two ways to implement the connection, one is synchronous and the other is asynchronous, and the asynchronous connection creates a new thread that will be responsible for the download action.  For synchronous connections, the current calling thread is blocked when the connection is downloaded and the traffic is processed. Many developers will think that a synchronized connection will block the main thread, which is a false view. A synchronous connection is a thread that blocks calls to it. If you create a sync connection in the main thread, yes, the main thread will block. But if you are not a synchronous connection that is opened from the main thread, it will be like an asynchronous connection. So this situation does not clog your main thread.  In fact, the main difference between synchronous and asynchronous is that running runtime creates a thread for an asynchronous connection, while a synchronous connection does not. 2. In order to be able to create an asynchronous request connection, we need to do the following.
1. Create a URL connection string of type nssring.
2. Convert the NSString type into a nsurl type.
3. Assign our URL object to the Nsurlrequest object, and if it is multiple connection requests, use Nsmutableurlrequest.4.   Create a Nsurlconnection connection instance, and then assign the URL request that we have defined to the past. We can create an asynchronous URL Connection object by Nsurlconnection the SendAsynchronousRequest:queue:completionHandler method. The parameters of this method are as follows:sendasynchronousrequestAsynchronous requestQueue  An operation queue, we can easily allocate and initialize an operation queue, which can then be added to this parameter according to our requirements.

Completionhandler

This is a block object, when our asynchronous connection operation completes, regardless of whether our asynchronous operation succeeds, will execute this block, this block object can receive the following three parameters:

1). A nsurlresopne, this object encapsulates the server returned to US response.

2). NSData, optional, this is the data we return through the URL request.

3). An object of type Nserror, if an error occurs in the request.

Attention:

SendAsynchronousRequest:queue:completionHandler: The method is not called in the main thread. So, if you want to perform a UI-related task, go back to the main thread.

Example:

- (void) sendasynnetwork{NSString*urlstring =@"http://www.apple.com"; Nsurl*url =[Nsurl urlwithstring:urlstring]; Nsurlrequest*urlrequest =[Nsurlrequest Requestwithurl:url]; Nsoperationqueue*queue =[[Nsoperationqueue alloc]init]; //sending an asynchronous request[Nsurlconnectionsendasynchronousrequest:URLRequest queue:queue completionhandler:^ (nsurlresponse *response, NSData *data, Nserror *connectionerror) {        if([Data length] >0&& Connectionerror = =Nil) {NSString*html =[[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"HTML =%@", HTML); //save data downloaded from the network to your hard drive //1. Get the storage path nsstring *documentsdir = [Nssearchpathfordirectoriesindomains (nsdocumentdirect            Ory, Nsuserdomainmask, YES) Objectatindex:0];  // Add the file name to the storage path, forming the path nsstring *filepath = [Documentsdir stringbyappendingpathcomponent: @" apple.html "            ];  // write data to a file and save to hard disk  [Data Writetofile:filepath atomically:yes]; NSLog (@"successfully saved the file to%@", FilePath); }        Else if([data length] = =0&& Connectionerror = =Nil) {NSLog (@"Nothing is downloaded"); }        Else if(Connectionerror! =Nil) {NSLog (@"Connectionerror happened =%@", Connectionerror); }    }];}
In earlier versions of the IOS SDK, URL connections used the delegation model, but now all use blocks, and you don't have to consider implementing the delegate method.

Two. Handling Timeouts in asynchronous connections

When creating an asynchronous request, you want to set a response timeout value to refine your application

Discuss:

When initializing the Nsurlrequest object and passing the object to the URL connection object, you can use RequestWithURL:cachePolicy:timeoutInterval: This class method to pass the timeout value to The timeOutInterval parameter.

Here is a detailed look at the second parameter cachepolicy: The parameter value is selected in the Nsurlrequestcachepolicy (cache policy) enumeration:

typedef ns_enum (Nsuinteger, Nsurlrequestcachepolicy)

{

1> nsurlrequestuseprotocolcachepolicy = 0, the default caching policy, if the cache does not exist, is obtained directly from the server. If the cache is present, the next action will be judged based on the Cache-control field in response, such as: Cache-control fields Must-revalidata, ask the server if the data is updated, and no updates are returned directly to the user to cache the data. If it has been updated, the service side is requested. 2> Nsurlrequestreloadignoringlocalcachedata = 1, ignoring local cache data, requesting the server directly. 3> Nsurlrequestreloadignoringlocalandremotecachedata = 4, ignoring the local cache, proxy server, and other mediations, directly requesting the source service side. 4> Nsurlrequestreloadignoringcachedata = Nsurlrequestreloadignoringlocalcachedata 5> Nsurlrequestreturncachedataelseload = 2, the cache is used, regardless of its validity (that is, ignoring the Cache-control field), no request server. 6> nsurlrequestreturncachedatadontload = 3, anyway load local cache. Fail without it. (determines that no network is currently used) 7> Nsurlrequestreloadrevalidatingcachedata = 5, the cached data must be validated by the server to be used ( Seems to be a case in nsurlrequestuseprotocolcachepolicy)}; Tips:url Loading System supports only the following 5 protocols in the default: only/HTTP and https://are available for caching policies. (1)/HTTP (2) https://(3) ftp://(4) file://(5) data://

// set a more detailed request the  second parameter cache policy The third parameter maximum wait time    Nsurlrequest *urlrequest1 = [Nsurlrequest requestwithurl:url cachepolicy: Nsurlrequestreloadignoringlocalandremotecachedata timeoutinterval:15.0f];

iOS network: Nsurlconnection for asynchronous requests

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.