iOS Development-File Download (4 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 @interface Yyviewcontroller () 4//File Data 5 @property (Nonatomic,strong) Nsmutableda  Ta *filedata;  6//File handle 7 @property (nonatomic,strong) Nsfilehandle *writehandle; 8//Current acquired data length 9 @property (nonatomic,assign) long long currentlength; 10//Full data length one @property (nonatomic,assign) long long sumlength; 12//is downloading the @property (nonatomic,assign,getter = isdownloading) BOOL downloading; 14//Request Object @property (Nonatomic,strong) nsurlconnection *cnnt; 16//Get button @property (weak, nonatomic) Iboutlet UIButton *btn; 18//Get progress bar @property (weak, nonatomic) Iboutlet Uiprogressview *progress; 20//Button click Event-(ibaction) star; @end @implementation Yyviewcontroller-(void) viewdidload [Super Viewdidload]; 30} 31 3 2-(Ibaction) Star {33//When the download is complete, click on the button text to download 34 35//Determine if the current download is currently being downloaded (self.isdownloading) {//If you are currently downloading, then click the button , the button changes to a paused state [self.btn settitle:@ "Download" forstate:uicontrolstatenormal]; Self.downLoading=no; 39 40/Cancel Send request [self.cnnt Cancel]; Self.cnnt=nil;         }else 44 {//If no download is currently available, click the button to start or continue downloading [self.btn settitle:@ "pause" forstate:uicontrolstatenormal]; 46 Self.downloading=yes; 47//Create download path Nsurl *url=[nsurl urlwithstring:@ "Http://192.168.1.53:8080/MJServer/resources/video.zip"]; 49 50//Create a request//Nsurlrequest *request=[nsurlrequest Requestwithurl:url]; Nsmutableurlrequest *request=[nsmutableurlrequest Requestwithurl:url]; 53 54//Set request header information in//self.currentlength byte section restart read NSString *value=[nsstring stringwith format:@ "bytes=%lld-", self.currentlength]; [Request Setvalue:value forhttpheaderfield:@ "Range"];  58 59//Send request (using proxy method) Self.cnnt=[nsurlconnection connectionwithrequest:request delegate:self]; //[self.cnnt start]; + #pragma mark-nsurlconnectiondatadeleGate Proxy Method 66/* 67 * When receiving a response from the server (connected to the server) will be called the connection */-(void): (nsurlconnection *) connection didreceiveresponse: (N     Surlresponse *) Response {#warning Determine if it is the first time to connect a if (self.sumlength) return; 73 74//1. Create File Save path 75 NSString *caches=[nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastObject]; NSString *filepath=[caches stringbyappendingpathcomponent:@ "Video.zip"]; 77 78 79 80//2. Create an empty file into the sandbox nsfilemanager *mgr=[nsfilemanager Defaultmanager]; 82//Just created the size is o bytes of the [Mgr Createfileatpath:filepath Contents:nil Attributes:nil]; 84 85//3. Create a file handle to write Data self.writehandle=[nsfilehandle Filehandleforwritingatpath:filepath]; 87 88//4. Get the full file length of the self.sumlength=response.expectedcontentlength; 90} 91 92/* 93 * Called when data is received from the server (may be called multiple times, only partial data is delivered at a time) 94 */-(void) connection: (Nsurlconnection *) connection Didreceiv EData: (NSData *) data 96 {97//cumulative received length 98 Self.curreNtlength+=data.length; 99//Calculate the progress value of double progress= (double) self.currentlength/self.sumlength;101 self.progress.progress=progress;10 2 103 104//1.1 points receive data. NSLog (@ "received data from the server! ---%d ", data.length); 106//writes data to the created empty file, but cannot use WriteToFile (overwrites) 107//To move to the end of the file 108 [Self.writehandle Seektoendo FFILE];109//From the current mobile location, write data (self.writehandle writedata:data];111}112 113/*114 * When the server's data is loaded it will call 115 */116-( void) Connectiondidfinishloading: (nsurlconnection *) connection117 {118 NSLog (@ "Download completed----%lld", self.sumlength); 119// Close connection, no longer input data in file [Self.writehandle closefile];121 self.writehandle=nil;122 123//Empty progress value 124 Self.curre ntlength=0;125 self.sumlength=0;126 127//Set button text for "already downloaded completed" [Self.btn settitle:@ "has been downloaded" forstate:uicontr olstatenormal];129 [self.btn setenabled:no];130}131/*132 * Request error (failed) call (Request timed out \ off net \ No net \, general refer to client Error) 133 */134-(void) con Nection: (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:

Tags: iOS development, network chapter

iOS Development-File Download (4 pause and resume)

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.