First, large file download
1. Scenario: Leveraging Nsurlconnection and its proxy approach
1> send a request
//1.URL
Nsurl *url = [Nsurl urlwithstring:@ "Http://localhost:8080/MJServer/resources/videos.zip"];
//2. Request
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
//3. Download (an asynchronous request is automatically initiated when the Conn object is created)
[Nsurlconnection connectionwithrequest:request delegate:self];
2> processing the data returned by the server in the proxy method
/**
when you receive a response from the server:
1. Create an empty file
2. Use a handle object to associate the empty file with the purpose of using the handle object to write the data behind the file conveniently
*/
-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response
{
//file path
NSString *caches = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) lastObject];
NSString *filepath = [Caches stringbyappendingpathcomponent:@ "Videos.zip"];
//Create an empty file into the sandbox
Nsfilemanager *mgr = [Nsfilemanager Defaultmanager];
[Mgr Createfileatpath:filepath Contents:nil Attributes:nil];
//Create a file handle to write data
Self.writehandle = [Nsfilehandle Filehandleforwritingatpath:filepath];
}
/**
use the Handle object to append data to the last face of the file when the file data returned by the server is received
*/
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data
{
//Move to the last side of the file
[Self.writehandle Seektoendoffile];
//write data to sandbox
[Self.writehandle Writedata:data];
}
/**
close the handle object when all data is received
*/
-(void) connectiondidfinishloading: (nsurlconnection *) connection
{
//Close file
[Self.writehandle CloseFile];
Self.writehandle = nil;
}
2. Note: Never use Nsmutabledata to splice data returned by the server
Ii. Nsurlconnection method for sending asynchronous requests
1.block form-Except for large file download, it can be used in this form
[Nsurlconnection sendasynchronousrequest:<# (Nsurlrequest *) #> queue:<# (Nsoperationqueue *) #> completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) {
}];
2. Proxy form-generally used in large file download
1.URL
Nsurl *url = [Nsurl urlwithstring:@ "http://localhost:8080/MJServer/login?username=123&pwd=123"];
2. Request
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
3. Download (after the Conn object is created, an asynchronous request is automatically initiated)
[Nsurlconnection connectionwithrequest:request delegate:self];
IOS nsurlconnection (large file download)