OC-16. large File Download

Source: Internet
Author: User

Big File Download Considerations
    • If you do not dump the downloaded files, it will cause a sharp increase in memory consumption, or even run out of memory resources, causing the program to terminate.
    • In the file download process usually occurs midway stop situation, if not to do processing, it is necessary to restart the download, waste traffic.
Solutions for large file downloads
    • Process the downloaded files, write the data to disk (usually in a sandbox), and avoid accumulating data in memory (nsurlconnection download), with every bit of data downloaded

      • Implementing write Data using the Nsfilehandle class
      • Implementing write Data using the Nsoutputstream class
    • When the download task terminates, log the location information at the end of the task so that the next time you start the download

Large file Download (nsurlconnection)
  • Breakpoint Download not supported
  • Download files using the Nsurlconnection proxy method
  • The task of transferring the downloaded file and recording the end location in the proxy method of the callback at different stages of the download task
  • To use the Nsfilehandle class to implement the download procedure for writing data ( 完整核心代码 )

    • Set related member properties

       /** the total length of the file to download */  @property (nonatomic, assign) Nsinteger contentlength; /** total length of downloaded files */ @property (nonatomic, assign) Nsinteger Currentlength/** file handle, used to implement file storage */ @property (Nonatomic, Strong) Nsfilehandle *handle;        
    • Create, send requests

      // 1. 创建请求路径NSURL *url = [NSURL URLWithString:@"此处为URL字符串"];// 2. 将URL封装成请求NSURLRequest *request = [NSURLRequest requestWithURL:url];// 3. 通过NSURLConnection,并设置代理[NSURLConnection connectionWithRequest:request delegate:self];
    • Comply with Agent protocol Nsurlconnectiondatadelegate, implement proxy method

      /*** the method that is called when the server response is received */-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nshttpurlresponse *) response{Get the total length of the file you want to downloadSelf. contentlength = [Response. allheaderfields[@ "Content-length"] integervalue];Stitching a file path in a sandboxNSString *filepath = [[Nssearchpathfordirectoriesindomains (Nscachesdirectory,Nsuserdomainmask,YES) Lastobject] stringByAppendingPathComponent:@ "Minion_15.mp4"];Creates a file of the specified path [[Nsfilemanager Defaultmanager] Createfileatpath:filepath contents:Nil attributes:NIL];To create a file handleSelf. Handle = [Nsfilehandle Filehandleforwritingatpath:filepath];}/*** the method that is called when receiving data from the server */-(void) Connection: (Nsurlconnection *) connection Didreceivedata: (NSData *) data{Navigates to the end of the file, stitching the file data returned by the server every time to the end of the file [Self. Handle Seektoendoffile];Writes a file to the sandbox through a file handle [Self. Handle Writedata:data];The total length of the downloaded file is splicedSelf. currentlength + = Data .length; //calculate download Progress cgfloat progress = 1.0 * Span class= "Hljs-keyword" >self.currentlength/self.contentlength;} /*** file is downloaded when the method */-(void) connectiondidfinishloading: ( Span class= "hljs-built_in" >nsurlconnection *) Connection{//close file handle and clear [self.handle CloseFile]; self.handle = nil;//empty downloaded file length self.currentlength = 0;}               
  • To use the Nsoutputstream class to implement the download procedure for writing data ( 部分代码,其他部分代码同上 )

    • Set Nsoutputstream member properties

      @property (nonatomic, strong) NSOutputStream *stream;
    • Initialize the Nsoutputstream object to open the output stream

      /** call */-When the server response is received (void) Connection: (Nsurlconnection *) connection didreceiveresponse: (nsurlresponse *) Response{//get the path to save the download data nsstring *cache = [nssearchpathfordirectoriesindomains ( Span class= "hljs-built_in" >nscachesdirectory, nsuserdomainmask, yes) Lastobject]; nsstring *filepath = [Cache Stringbyappendingpathcomponent:response.suggestedfilename"; //use Nsoutputstream to write data to the FilePath file, if the append parameter is yes, it will be written to the end of the file .stream = [[nsoutputstream alloc] InitToFileAtPath: FilePath append:yes]; //Open Data stream [self.stream Open];}  
    • Write file data

      /**接收到数据的时候调用*/- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{[self.stream write:[data bytes] maxLength:data.length];}
    • Turn off the output stream

      /**数据下载完毕的时候调用*/- (void)connectionDidFinishLoading:(NSURLConnection *)connection{[self.stream close];}
Large file Download (nsurlsession)
  • Support breakpoint download, automatically record the location of breakpoints when stopping download
  • Compliance with Nsurlsessiondownloaddelegate Protocol
  • Using nsurlsession to download large files, the downloaded files will be automatically written to the sandbox Temp folder tmp
  • After downloading, it is usually necessary to move the downloaded files elsewhere (the data in the TMP folder is deleted periodically), usually in the cache folder
  • Detailed download steps

    • Set Download task task as member variable

      @property (nonatomic, strong) NSURLSessionDownloadTask *task;
    • Get Nsurlsession Object

      NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    • Initializing the Download Task task

      self.task = [session downloadTaskWithURL:(此处为下载文件路径URL)];
    • Implementing Proxy methods

      /** each time the data is written to a temporary file, the method is called once, usually in this method to get the download Progress */-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) Downloadtask didwritedata: (int64_t) Byteswritten Totalbyteswritten: (int64_t) Totalbyteswritten totalbytesexpectedtowrite: (int64_t) totalbytesexpectedtowrite{Calculate Download ProgressCGFloat progress =1.0 * TOTALBYTESWRITTEN/TOTALBYTESEXPECTEDTOWRITE;}/** the method that is called when the task terminates, typically used for breakpoint download */-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) Downloadtask Didresumeatoffset: (int64_t) Fileoffset expectedtotalbytes: (int64_t) expectedtotalbytes{Fileoffset: The offset when the download task is aborted}/** is called when an error is encountered, the error parameter can only pass the client's errors */-(void) Urlsession: (Nsurlsession *) Session task: (Nsurlsessiontask *) Task Didcompletewitherror: (Nserror *) error{}/** when the download is complete, you need to cut the file to a folder that can be saved for a long time */-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) Downloadtask Didfinishdownloadingtourl: (nsurl *) Location{//generate file long-term saved path nsstring *file = [nssearchpathfordirectoriesindomains ( Span class= "hljs-built_in" >nscachesdirectory, nsuserdomainmask, yes) Lastobject] Stringbyappendingpathcomponent:downloadtask .response.suggestedfilename]; //get file handle nsfilemanager *filemanager = [ nsfilemanager Defaultmanager]; //through the file handle, cut the file to the long-term saved path of the file [FileManager moveitematurl:location Tourl:[nsurl Fileurlwithpath:file] error:nil];}      
    • Operation Task Status

      /**开始/继续下载任务*/[self.task resume];/**暂停下载任务*/[self.task suspend];

OC-16. large File Download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.