Large file download in iOS (single-threaded download)

Source: Internet
Author: User

The main point is to pay attention to the customer service to the server when the request, in the request header is able to set the server to return the data from where to end.

When the server responds to the client, it can get the exact type and size of the data returned by the server.

#import <Foundation/Foundation.h> @interface The remote URL (the path of the connection server) that the zyfiledownload:nsobject//needs to download @property ( Nonatomic, Strong) nsstring *urlstr;//file storage path @property (nonatomic, strong) NSString *goalpath;//Whether you are downloading @property ( Nonatomic, ReadOnly, getter= isdownloading) BOOL downloading;//monitoring Download Progress @property (nonatomic, copy) void (^progresshandler ) (double progress);//Callback @property (nonatomic, copy) void (^finishhandler) After download is completed,//callback @property after download failed (nonatomic, copy void (^failurehandler) (Nserror *error);//Start download-(void) start;//pause download-(void) pause; @end/* file is generally saved at the address below, Documents in the path of the file needs to be synchronized, the file consumption performance, the TMP path will be deleted at any time so generally saved in the library\caches path to obtain this path: nsstring *caches = [Nssearchpathfordi    Rectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject]; NSString *filepath = [caches stringbyappendingpathcomponent:@ "filename. suffix name"]; */#import "ZYFileDownLoad.h" @interface zyfiledownload () <nsurlconnectiondatadelegate>//the currently downloaded data length @property ( Nonatomic, assign) long long currentlength;//Connection Object @Property (Nonatomic, Strong) nsurlconnection *connection;//total file length @property (nonatomic, assign) long long totallength;// Write file handle @property (Nonatomic, strong) Nsfilehandle *writehandle; @end @implementation zyfiledownload-(void) start{[    Self.urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];        Nsurl *url = [Nsurl URLWithString:self.urlStr];        Nsmutableurlrequest *request = [[Nsmutableurlrequest alloc] initwithurl:url]; Set the request header information, this indicates that this data range is currentprogress to the end of the file (that is, only set the beginning from where to download) nsstring *value = [NSString stringwithformat:@ "bytes=%    Lld-", Self.currentlength];        [Request Setvalue:value forhttpheaderfield:@ "Range"];        Self.connection = [nsurlconnection connectionwithrequest:request delegate:self]; _downloading = YES;}    -(void) pause{[self.connection Cancel];    Self.connection = nil; _downloading = NO;} #pragma mark----nsurlconnectiondatadelegate//call-(void) connection: (Nsurlconnection *) connection when the request error (failed) Didfailwitherror: (Nserror *) Error{if (self.failurehandler) {Self.failurehandler (error); }}-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{if (   Self.totallength) return;    When the response has been answered, there is no need to reply again (mainly to pause the download, and then reply to the download operation)//create an empty file into the sandbox nsfilemanager *manager = [Nsfilemanager Defaultmanager];        [Manager CreateFileAtPath:self.goalPath Contents:nil Attributes:nil];        Create file handle to write Data Self.writehandle = [Nsfilehandle FileHandleForWritingAtPath:self.goalPath]; Gets the length of the full file (when the server responds to the client, the specific file length is returned) Self.totallength = Response.expectedcontentlength;} When the data received to the server is called (may be called multiple times, each call will only pass part of the data)-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *)  data{Self.currentlength + = [data length];        Download complete, Cumulative length//progress double progress = (double) self.currentlength/self.totallength;    The block callback allows you to execute the operation if (Self.progresshandler) {Self.progresshandler (progress) inside the block; }//Move end of file, append data to tail [Self.writehanDle Seektoendoffile]; [Self.writehandle Writedata:data];}    -(void) connectiondidfinishloading: (nsurlconnection *) connection{//Download complete, please attribute self.currentlength = 0;        self.totallength = 0;        if (self.currentlength = = self.totallength) {//download complete, close connection [Self.writehandle CloseFile];    Self.writehandle = nil;    } if (Self.finishhandler) {Self.finishhandler (); }} @end

Large file download in iOS (single-threaded 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.