Using Nsurlconnection to process HTTP synchronous and asynchronous requests in IOS _ios

Source: Internet
Author: User
Tags gcd

First, the introduction

After the iOS7, Nsurlsession basically replaced the nsurlconnection for network development, after iOS9, nsurlconnection related methods are completely discarded, iOS system has backward-compatible features, Although Nsurlconnection has been deprecated, its approach can still be used in development, and it is sometimes necessary to use the Nsurlconnection class if it needs to be compatible with a very low version of the iOS system.

Second, the use of nsurlconnection for synchronization requests

For network requests, there are two types of synchronous and asynchronous, synchronization means that the program code will be stuck at the request before the result of the request is returned, and the code will not be executed after the request is sent, when the return data is received in the child thread while the code is executed, after the return data is received, Use callback to notify the main thread to do the processing.

Use the following method for Nsurlconnection synchronization requests:

    NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSLog(@"%@",data);
    NSLog(@"继续执行");
The print information shown in the following illustration shows that the following code is executed when the data returns to the end:

Iii. Asynchronous requests using Nsurlconnection

There's a big downside to making requests in a synchronized way, in the network request, the return of data often need a certain time, can not be instantaneous completion, the use of synchronization will lead to the interface card dead, no hint can not interact with any user operation, so, it is likely to give the user the illusion of death card.

The Nsurlconnection class provides two ways to perform asynchronous request operations.

1. Asynchronous request using Block method

A block-mode asynchronous request is made using the following code, in which the requested return data and data information are passed in as parameters:

    NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    //其中的queue参数决定block中的代码在哪个队列中执行
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSLog(@"%@",data);
    }];
    NSLog(@"继续执行");

2. Asynchronous request method using proxy callback

First comply with the protocol and life A variable nsdata is used to receive data:

@interface ViewController ()<NSURLConnectionDataDelegate>
{
    NSMutableData * _data;
}
@end
Use the following code to make a request:

    _data = [[NSMutableData alloc]init];
    NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
Once the request is issued, the following proxy method is invoked at once to monitor the request process and obtain the data:

-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{
    //Start receiving data
    [_data setlength:0];

-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{
   //receiving data
    [_data appenddata:data];
}
-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{
    Failed to receive data
    NSLog (@ "%@", error);

-(void) connectiondidfinishloading: (nsurlconnection *) connection{
   //Receiving data completion
     NSLog (@ "%@", _data);
}

Iv. examples
1. Asynchronous download via nsurlconnection:
Nsurlconnection provides two ways to implement a connection, one of which is asynchronous, and the asynchronous connection creates a new thread that will be responsible for downloading the action. For a synchronous connection, the current calling thread is blocked when the connection is downloaded and the traffic is processed.
Many developers would argue that a synchronized connection would block the main thread, which is a false view. A synchronized 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 synchronized connection that is opened from the main thread, it will be like an asynchronous connection. So this is not going to clog your main thread. In fact, the main difference between synchronization and Asynchrony is that running runtime creates a thread for an asynchronous connection, and a synchronous connection does not.

Asynchronousrequest Connection
-(void) fetchapplehtml{
NSString *urlstring = @ "http://www.apple.com";
Nsurl *url = [Nsurl urlwithstring:urlstring];
Nsurlrequest *urlrequest = [Nsurlrequest Requestwithurl:url];
Nsurlrequest *urlrequest = [Nsurlrequest requestwithurl:url cachepolicy: Nsurlrequestreloadignoringlocalandremotecachedata timeoutinterval:30.0f]; Maximal timeout is 30s

Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];
[Nsurlconnection sendasynchronousrequest:urlrequest queue:queue completionhandler:^ (NSURLResponse *response, NSData *data, Nserror *connectionerror) {
if ([data length] > 0 && connectionerror = = nil) {
NSString *documentsdir = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomainMask, YES) OBJECTATINDEX:0];
NSString *filepath = [Documentsdir stringbyappendingpathcomponent:@ "apple.html"];
[Data Writetofile:filepath Atomically:yes];
NSLog (@ "Successfully saved the file to%@", FilePath);
NSString *html = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];
NSLog (@ "html =%@", html);
}else if ([data length] = = 0 && Connectionerror = = nil) {
NSLog (@ "Nothing is downloaded.");
}else if (connectionerror!= nil) {
NSLog (@ "Error happened =%@", connectionerror);
}
}];
}

2. Sync download via nsurlconnection:
Using the Nsurlconnection SendSynchronousRequest:returningResponse:error: Class method, we can make synchronization requests. When creating a synchronized network connection, we need to understand that it's not that our sync connection will clog our main thread, and if this sync connection is created on the main thread, then it will clog our main thread, and in other cases it will not necessarily clog our main thread. If you initialize a synchronized connection on the GCD global concurrency queue, you are not actually blocking our main thread.
Let's initialize the first sync connection and see what happens. In the example, we will try to get the Yahoo! US site home page content:

Synchronousrequest Connection
-(void) fetchyahoodata{
NSLog (@ "We are here ...");
NSString *urlstring = @ "http://www.yahoo.com";
Nsurl *url = [Nsurl urlwithstring:urlstring];
Nsurlrequest *urlrequest = [Nsurlrequest Requestwithurl:url];
Nsurlresponse *response = nil;
Nserror *error = nil;
NSLog (@ "Firing synchronous URL connection ...");
NSData *data = [nsurlconnection sendsynchronousrequest:urlrequest returningresponse:&response error:&error];
if ([data length] > 0 && error = = nil) {
NSLog (@ "%lu bytes of data was returned.", (unsigned long) [data length]);
}else if ([data length] = = 0 && Error = = nil) {
NSLog (@ "No data is return.");
}else if (Error!= nil) {
NSLog (@ "Error happened =%@", error);
}
NSLog (@ "We are done.");

}
/*
|
| As we know, it'll chock main thread when we call Sendsynchronousrequest on main thread,,,, change below
|
V
*/
Call Sendsynchronousrequest on GCD pool
-(void) fetchyahoodata2_gcd{
NSLog (@ "We are here ...");
NSString *urlstring = @ "http://www.yahoo.com";
NSLog (@ "Firing synchronous URL connection ...");
dispatch_queue_t dispatchqueue = dispatch_get_global_queue (dispatch_queue_priority_default, 0);
Dispatch_async (Dispatchqueue, ^{
Nsurl *url = [Nsurl urlwithstring:urlstring];
Nsurlrequest *urlrequest = [Nsurlrequest Requestwithurl:url];
Nsurlresponse *response = nil;
Nserror *error = nil;
NSData *data = [nsurlconnection sendsynchronousrequest:urlrequest returningresponse:&response error:&error];
if ([data length] > 0 && error = = nil) {
NSLog (@ "%lu bytes of data was returned.", (unsigned long) [data length]);
}else if ([data length] = = 0 && Error = = nil) {
NSLog (@ "No data was returned.");
}else if (Error!= nil) {
NSLog (@ "Error happened =%@", error);
}
});
NSLog (@ "We are done.");

}

To view the results of the run output, respectively:
Synchronous download on main thread without GCD

Synchronous download on main thread with GCD

You can see that invoking a synchronous download on the main thread blocks the current thread, while using GCD does not.

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.