(1) Create the nsurlsession and set up the agent, through the Nsurlsessiondownloadtask and proxy way to complete the large file download
//1. Create Nsulrsession, set agent self.session = [nsurlsession sessionwithconfiguration:[ Nsurlsessionconfiguration Defaultsessionconfiguration] Delegate:self delegateQueue:[ Nsoperationqueue Mainqueue]]; //2. Create task nsurl *url = [NSURL Urlwithstring:@ "Http://120.25.226.186:32812/resources/videos/minion_01.mp4"]; self.downloadtask = [self.session Downloadtaskwithurl:url]; //3. Execute task [self.downloadTask Resume];
(2) Description of common agent methods
/* 1. When the download data is received, you can listen to the progress of the file download in this method. The method is called multiple times Totalbyteswritten: The size of the data that has been written to the file Totalbytesexpectedtowrite: The total size of the current file Byteswritten: File data size for this download */-(void) Urlsession: (nonnullNsurlsession *) session Downloadtask: (nonnullNsurlsessiondownloadtask *) Downloadtask didwritedata: (int64_t) Byteswritten Totalbyteswritten: (int64_t) Totalbyteswritten totalbytesexpectedtowrite: (int64_t) Totalbytesexpectedtowrite/* 2. When you resume the download, call the method Fileoffset: After the restore, from where to develop the file download Expectedtotalbytes: The total size of the file data */-(void) Urlsession: (nonnull nsurlsession *) session Downloadtask: (nonnull nsurlsessiondownloadtask *) Downloadtask Didresumeatoffset: (int64_t) FileOffset Expectedtotalbytes: (int64_t) Expectedtotalbytes/* 3. Call this method after the download is complete */-( void) Urlsession: (nonnull nsurlsession *) session Downloadtask: (nonnull nsurlsessiondownloadtask *) Downloadtask Didfinishdownloadingtourl: (Nonnull nsurl *) Location/* 4. Call if the request fails, then error has a value of */-(void) urlsession: (nonnull nsurlsession *) session task: (nonnull Nsurlsessiontask *) Task Didcompletewitherror: (Nullable nserror *) error
(3) Implement breakpoint download related code
If the task is canceled, then it cannot be recovered.[Self.downloadtask Cancel];//if this is the way to cancel the task, then the method will save the current file download information resumedata self.downloadtask cancelbyproducingresumedata:^ (nsdata * __nullable resumedata) { self.resumedata = Resumedata;}]; -----------//continue to download //first through the previously saved Resumedata information, create a download task self.downloadtask = [self.session downloadtaskwithresumedata:self . Resumedata]; [self.downloadtask resume];
(4) Calculate current Download Progress
//获取文件下载进度 self.progress.progress = 1.0 * totalBytesWritten/totalBytesExpectedToWrite;
(5) Limitations
01 如果用户点击暂停之后退出程序,那么需要把恢复下载的数据写一份到沙盒,代码复杂度更02 如果用户在下载中途未保存恢复下载数据即退出程序,则不具备可操作性
Large file download with Nsurlsessiondownloadtask-Listen for download progress