nsurlconnection for large file downloads
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(finished creatingConnobject, an asynchronous request is automatically initiated)
[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 to the in the sandbox
Nsfilemanager *mgr = [Nsfilemanager Defaultmanager];
[Mgr Createfileatpath:filepath contents:Nilattributes:Nil];
// Create a file handle to write data to
Self. writehandle = [Nsfilehandle Filehandleforwritingatpath:filepath];
//get the total size of the file
Self.Totallength= Response.Expectedcontentlength;
}
/**
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 a file
[ Self. Writehandle Seektoendoffile];
// writing data to a sandbox
[ Self. Writehandle Writedata:data];
//the length of the cumulative file
Self.Currentlength+ = data.length;
NSLog(@"Download Progress:%f ", (Double) Self.Currentlength/ Self.Totallength);
Self.Circleview.Progress= (Double) Self.Currentlength/ Self.Totallength;
}
/**
close the handle object when all data is received
*/
- (void) connectiondidfinishloading: (nsurlconnection *) connection
{ Self.Currentlength= 0;
Self.Totallength= 0;
// Close File
[ Self. Writehandle CloseFile];
Self. Writehandle =Nil;
}
Note: Never use nsmutabledata to splice data returned by the server
Nsurlconnection for large file downloads