nsurlsession Implementation Download (proxy)
-(void) downloadTask2
{
{
nsurlsessionconfiguration *cfg = [nsurlsessionconfigurationdefaultsessionconfiguration];
//1.GetSessionObject
nsurlsession *session = [nsurlsessionsessionwithconfiguration: CFGDelegate: SelfDelegatequeue:[NsoperationqueueMainqueue]];
//2.Create a downloadTask
Nsurl *url = [Nsurlurlwithstring:@ "Http://localhost:8080/MJServer/resources/test.mp4"];
//Nsurlsessiondownloadtask *task = [Session Downloadtaskwithurl:url completionhandler:^ (Nsurl *location, NSURLRes Ponse *response, Nserror *error) {
//NSLog (@ "%@", location);
// }];
Nsurlsessiondownloadtask *task = [Session Downloadtaskwithurl: url];
//3.Start Task
[Task Resume];
// If the download task is set toCompletionhandlerthisBlock, also implements the download proxy method, the priority implementationBlock
}
Note:nsurlsessiondownloadtask After the download is complete, save the data in the TMP temp file in the sandbox, you need to set the temporary filecut or copy a temporary fileCachesfolder.
#pragma mark-nsurlsessiondownloaddelegate
/**
* called when the download is complete
*
* @param Location path to temporary files (downloaded files)
*/
- (void) Urlsession: (nsurlsession*) session Downloadtask: (Nsurlsessiondownloadtask*) Downloadtask Didfinishdownloadingtourl: (Nsurl*) Location
{
//Location: path to temporary files (downloaded files)
NSString *caches = [Nssearchpathfordirectoriesindomains(nscachesdirectory,Nsuserdomainmask,YES) Lastobject];
//Response.suggestedfilename : recommended file name, generally consistent with the server-side file name
NSString *file = [Cachesstringbyappendingpathcomponent:d ownloadtask.Response.Suggestedfilename];
// cut or copy a temporary fileCachesfolder
Nsfilemanager *mgr = [NsfilemanagerDefaultmanager];
//Atpath: file path before clipping
//Topath: the file path after clipping
[Mgr Moveitematpath: Location.PathTopath: FileError:Nil];
}
/**
* called when resuming a download
*/
- (void) Urlsession: (nsurlsession*) session Downloadtask: (Nsurlsessiondownloadtask*) Downloadtask Didresumeatoffset: (int64_t) Fileoffset expectedtotalbytes: (int64_t) expectedtotalbytes
{
}
/**
* called (may be called multiple times) whenever a portion of the download is completed (written)
*
* @param Byteswritten How much did this call write?
* @param Totalbyteswritten how many lengths have been written to the sandbox?
* @param Totalbytesexpectedtowrite total length of file
*/
- (void) Urlsession: (nsurlsession*) session Downloadtask: (Nsurlsessiondownloadtask*) Downloadtask didwritedata: (int64_t) Byteswritten Totalbyteswritten: (int64_t) Totalbyteswritten Totalbytesexpectedtowrite: (int64_t) Totalbytesexpectedtowrite
{
Double progress = (Double) Totalbyteswritten/totalbytesexpectedtowrite;
NSLog(@"Download Progress---%f ", progress);
}
Nsurlsession implementation Download (proxy)