The connection of the previous article is a synchronous connection, this time in detail about the way the network connection
One, there are two types of connection: synchronous and asynchronous
Synchronous Connection
1, using the [nsurlconnection sendsynchronousrequest:] method
2, there will be a phenomenon of Dayton
asynchronous connections are divided into two types:block and delegate
1), Block is used by [nsurlconnection sendasynchronousrequest:requset queue:[nsoperationqueue Currentqueue] completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) {
}];
This method requires two parameters: request requests
queue queues, typically currentqueue
Note:
the code inside the block does not execute immediately, but only after the server has requested the data.
2), How to use the delegate:
1, an asynchronous connection with delegate encapsulates the data download progress in the protocol, so this connection is typically used
2, with delegate connection is asynchronous connection, interface first out, then to obtain data, so the problem and block like
Note:
agent in a named didreceivedata: Method, The data is not already downloaded data, you need to splice
Second, synchronous connection step
nsurl *url = [nsurl urlwithstring: URL string ];
nsurlrequest *requset = [nsurlrequest requestwithurl: URL cachepolicy:( nsurlrequestuseprotocolcachepolicy) timeoutinterval:[];
nsurlresponse *response = nil;
nserror *error = nil;
nsdata *data = [nsurlconnection sendsynchronousrequest: Requset returningresponse: &response error:&error];
Third, asynchronous connection
1,block method
nsurl *url = [nsurl urlwithstring: URL string ];
nsurlrequest *requset = [nsurlrequest requestwithurl: URL cachepolicy:( nsurlrequestuseprotocolcachepolicy) timeoutinterval:[];
[nsurlconnection sendasynchronousrequest: Requset queue: [nsoperationqueue Currentqueue] completionhandler: ^ (nsurlresponse *response, nsdata *data, Nserror *connectionerror) {
Here you can parse the data, show the pictures, etc.
}];
2, Proxy method
nsurl *url = [nsurl urlwithstring: URL string ];
nsurlrequest *request = [nsurlrequest requestwithurl: URL cachepolicy: Nsurlrequestuseprotocolcachepolicy timeoutinterval:];
[[[nsurlconnection alloc] initwithrequest: Request delegate:self] Autorelease];
The proxy method after accepting the agreement has
Receive Response
-(void) connection: (nsurlconnection *) connection didreceiveresponse: (nsurlresponse * ) response{
}
receiving Data
-(void) connection: (nsurlconnection *) connection didreceivedata: (nsdata *) data{
}
Data Acquisition Complete
-(void) connectiondidfinishloading: (nsurlconnection *) connection{
}
Get failed
-(void) connection: (nsurlconnection *) connection didfailwitherror: (nserror *) error{
}
Network connectivity for iOS network programming (ii)