iOS Development Network Chapter-File download (four • Pause and resume)

Source: Internet
Author: User

iOS Development Network Chapter-File download (four • Pause and resume)

One, Range simple description

You can specify the size of each packet to be downloaded from the network by setting the request header range

Range Example

bytes=0-499 from 0 to 499 of the first 500 bytes

bytes=500-999 from 500 to 999 of the second 500 bytes

bytes=500- All bytes since 500 bytes

bytes=-500 last 500 bytes

bytes=500-599,800-899 Specify several ranges at the same time

Range Summary

- used to separate

The preceding number indicates the starting byte number

The following array represents the number of cutoff bytes and does not represent the end

, for grouping, you can specify more than one range at a time, but rarely

Second, code example

1 #import "YYViewController.h"2 3 @interfaceYyviewcontroller ()4 //File Data5@property (nonatomic,strong) Nsmutabledata *FileData;6 //file handle7@property (nonatomic,strong) Nsfilehandle *Writehandle;8 //the currently acquired data length9@property (nonatomic,assign)Long Longcurrentlength;Ten //Full Data length One@property (nonatomic,assign)Long Longsumlength; A //are you downloading -@property (Nonatomic,assign,getter =isdownloading) BOOL downloading; - //Request Object the@property (nonatomic,strong) nsurlconnection *cnnt; - //Get button -@property (Weak, nonatomic) Iboutlet UIButton *btn; - //get the progress bar +@property (Weak, nonatomic) Iboutlet Uiprogressview *progress; - //button click event +-(ibaction) star; A  at @end -  - @implementationYyviewcontroller -  -- (void) Viewdidload - { in [Super Viewdidload]; - } to  +-(ibaction) star { -     //when the download is complete, click the button text to become downloaded the  *     //determine whether you are currently downloading $     if(self.isdownloading) {//If you are currently downloading, click the button and the button changes to a paused state.Panax Notoginseng[Self.btn Settitle:@"Download"Forstate:uicontrolstatenormal]; -self.downloading=NO; the          +         //Cancel Send Request A [self.cnnt Cancel]; theSelf.cnnt=Nil; +}Else -{//If there is no current download, then click the button to start or continue downloading $[Self.btn Settitle:@"Pause"Forstate:uicontrolstatenormal]; $self.downloading=YES; -         //Create a download path -Nsurl *url=[nsurl urlwithstring:@"Http://192.168.1.53:8080/MJServer/resources/video.zip"]; the          -         //Create a requestWuyi //nsurlrequest *request=[nsurlrequest Requestwithurl:url]; theNsmutableurlrequest *request=[Nsmutableurlrequest Requestwithurl:url]; -          Wu         //Set Request header information -         //self.currentlength byte partial restart read About         nsstring *value=[nsstring stringwithformat:@ "bytes=%lld-" , Self.currentlength]; $        [Request Setvalue:value forhttpheaderfield:@ "Range"]; -          -         //send a request (using proxy method) -Self.cnnt=[nsurlconnection Connectionwithrequest:requestDelegate: self]; A //[self.cnnt start]; +     } the } -  $ #pragmaMark-nsurlconnectiondatadelegate Proxy method the /* the * When the response to the server is received (the server is connected) , the the  */ the-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) Response - {#warning determine if the first connection to the Self.sumlength return; the      About     //1. Create a file save path theNSString *caches=[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject]; theNSString *filepath=[caches stringbyappendingpathcomponent:@"Video.zip"]; the  +      -      the     //2. Create an empty file into the sandboxBayiNsfilemanager *mgr=[Nsfilemanager Defaultmanager]; the     //the size you just created is o bytes the [Mgr Createfileatpath:filepath contents:nil Attributes:nil]; -      -     //3. Create a file handle to write data theself.writehandle=[Nsfilehandle Filehandleforwritingatpath:filepath]; the      the     //4. Get the full file length theSelf.sumlength=response.expectedcontentlength; - } the  the /* the * Called when data is received from the server (may be called multiple times, only partial data is passed at a time)94  */ the-(void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) Data the { the     //accumulate the received data length98self.currentlength+=data.length; About     //Calculate Progress Values -     DoubleProgress= (Double) self.currentlength/self.sumlength;101self.progress.progress=progress;102     103     104     //1.1 points to receive data.  theNSLog (@"receive data from the server! ---%d", data.length);106     //writes data to the created empty file, but cannot use WriteToFile (overwrites)107     //move to the end of a file108 [Self.writehandle seektoendoffile];109     //writes data from the position currently being moved the [Self.writehandle Writedata:data];111 } the 113 /* the * When the server's data is loaded, it will be called the  */ the-(void) Connectiondidfinishloading: (Nsurlconnection *) Connection117 {118NSLog (@"Download complete----%LLD", self.sumlength);119     //closes the connection and no longer enters data in the file - [Self.writehandle CloseFile];121self.writehandle=Nil;122     123     //Empty Progress Values124Self.currentlength=0; theSelf.sumlength=0;126     127     //Set the button text to "already downloaded done" -[Self.btn Settitle:@"has been downloaded to complete"Forstate:uicontrolstatenormal];129 [self.btn Setenabled:no]; the }131 /* the * Request error (failure) when called (Request timeout \ network \ No net \, usually refers to client error)133  */134-(void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) Error135 {136 }137 @end

Note: Critical code

Re-start reading from Self.currentlength byte section

NSString *value=[nsstring stringwithformat:@ "bytes=%lld-", self.currentlength];

[Request Setvalue:value forhttpheaderfield:@ "Range"];

Simulator Operating Condition:

Program Start Screen:

Click the Download button to start downloading the file, and the button's prompt text becomes paused.

After the download is paused, click the Download button to continue the previous download.

After the download completes the interface effect:

When the download is complete, review the project sandbox:

Related Article

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.