1. synchronous download (poor interaction, prone to freezing, usually used only when downloading data is small or has specific requirements ).After a synchronous request is sent, the program stops user interaction until the server returns data.
// Step 1: Create a URL
NSURL * pURL = [NSURLURLWithString: URL];
// Step 2: Create a request
NSURLRequest * pRequest = [NSURLRequestrequestWithURL: pURL cachePolicy: NSURLRequestUseProtocolCachePolicytimeoutInterval: 60];
// Step 3: establish a connection
NSError * pError = nil;
NSURLResponse * pRespond = nil;
// Initiate a request to the server (after the request is initiated, the thread will wait for the server to respond until the maximum response time is exceeded)
NSData * pData = [NSURLConnectionsendSynchronousRequest: pRequest returningResponse: & pRespond error: & pError];
// Output the obtained result
NSLog (@ "pData = % @", pData );
// Output error message
NSLog (@ "pError = % @", [pErrorlocalizedDescription]);
Ii. asynchronous download
Asynchronous download supports downloading data from applications in the background. code execution is not blocked while waiting for the download to complete. The asynchronous connection steps are as follows:
/* Asynchronous request */
// 1. Obtain the network resource path (URL)
NSURL * pURL1 = [NSURLURLWithString: URL];
// 2. Create a request based on the URL
NSURLRequest * pRequset1 = [NSURLRequestrequestWithURL: pURL1 cachePolicy: NSURLRequestUseProtocolCachePolicytimeoutInterval: 60];
// 3. (difference from Synchronous requests) Initiate a request and complete data acquisition through the delegate mode callback
[NSURLConnectionconnectionWithRequest: pRequset1 delegate: self];
Note: The NSURLConnectionDataDelegate protocol is used in asynchronous requests, and the delegate object is itself. There are four frequently used methods. We put the obtained data in self. pData and its type is NSMutableData.
// 1. Server Response callback Method
-(Void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response
{
NSLog (@ "server response ");
Self. pData = [NSMutableDatadataWithCapacity: 5000];
}
// 2. The service returns data and the client starts to accept it (data is the returned data)
-(Void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data
{
NSLog (@ "server returned data ");
// Put the returned data in the cache
[Self. pDataappendData: data];
}
// 3. Callback method after data is accepted
-(Void) connectionDidFinishLoading :( NSURLConnection *) connection
{
NSLog (@ "data accepted ");
NSLog (@ "pData = % @", self. pData );
}
// 4. method called when data fails to be accepted
-(Void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error
{
NSLog (@ "failed to accept data, cause of failure: % @", [error localizedDescription]);
}