iOS Development Network chapter-Multi-threaded breakpoint Download
Description: This article describes multi-threaded breakpoint downloads. The project uses Apple's own class to enable multiple threads to download a larger file at the same time. Because the implementation process is more complex, the complete code is posted below.
Implementation ideas: Download start, create a file with the same size to download (if the file to download is 100M, then create a 100M file in the sandbox, and then calculate the download volume of each segment, open multiple threads to download the data of each segment, write the corresponding file section).
The main classes used in the project are as follows:
The implementation code is completed as follows:
Code in the host controller:
#import"YYViewController.h"#import"YYFileMultiDownloader.h"@interface Yyviewcontroller () @property (nonatomic, strong) Yyfilemultidownloader*Filemultidownloader, @end @implementation yyviewcontroller-(Yyfilemultidownloader *) filemultidownloader{if(!_filemultidownloader) {_filemultidownloader=[[Yyfilemultidownloader alloc] init]; //the file remote URL that needs to be downloaded_filemultidownloader.url =@"Http://192.168.1.200:8080/MJServer/resources/jre.zip"; //where are the files saved?NSString *caches =[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject]; NSString*filepath = [Caches stringbyappendingpathcomponent:@"Jre.zip"]; _filemultidownloader.destpath=filepath; } return_filemultidownloader;}- (void) viewdidload{[Super Viewdidload]; }- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{[Self.filemultidownloader start];} @end
Customizing a base class
YYFileDownloader.h file
#import <Foundation/Foundation.h>@interface yyfiledownloader:nsobject{BOOL _downloading;}/** * The remote URL of the file to be downloaded (the path of the connection server)*/@property (nonatomic, copy) NSString*URL;/** * File storage path (where files are downloaded)*/@property (nonatomic, copy) NSString*DestPath;/** * is downloading (there is no download, only the inside of the downloader to know)*/@property (nonatomic,ReadOnly, getter =isdownloading) BOOL downloading;/** * To monitor the download progress*/@property (nonatomic, copy)void(^progresshandler) (Doubleprogress);/** * Start (resume) Download*/- (void) Start;/** * Pause Download*/- (void) pause; @end
YYFILEDOWNLOADER.M file
1 " YYFileDownloader.h " 2 3 @implementation Yyfiledownloader 4 @end
The Downloader class inherits from the Yyfiledownloader class
YYFileSingDownloader.h file
" YYFileDownloader.h " @interface Yyfilesingledownloader:yyfiledownloader /* * * */ Longlong begin; /* * * */ Longlong end; @end
YYFILESINGDOWNLOADER.M file
#import"YYFileSingleDownloader.h"@interface Yyfilesingledownloader ()<NSURLConnectionDataDelegate>/** * Connection object*/@property (nonatomic, strong) Nsurlconnection*Conn;/** * File handle for writing data*/@property (nonatomic, strong) Nsfilehandle*Writehandle;/** * Length of the currently downloaded data*/@property (nonatomic, assign)Long Longcurrentlength, @end @implementation yyfilesingledownloader-(Nsfilehandle *) writehandle{if(!_writehandle) {_writehandle=[Nsfilehandle FileHandleForWritingAtPath:self.destPath]; } return_writehandle;}/** * Start (resume) Download*/- (void) start{Nsurl*url =[Nsurl URLWithString:self.url]; //The default is a GET requestNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; //Set Request header informationNSString *value = [NSString stringWithFormat:@"Bytes=%lld-%lld", Self.begin +self.currentlength, Self.end]; [Request Setvalue:value Forhttpheaderfield:@"Range"]; Self.conn= [Nsurlconnection connectionwithrequest:requestDelegate: Self]; _downloading=YES;}/** * Pause Download*/- (void) pause{[self.conn Cancel]; Self.conn=Nil; _downloading=NO;}#pragmaMark-nsurlconnectiondatadelegate Proxy method/** 1. When the response to the server is accepted (the server is connected) it calls the*/- (void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{}/** 2. When 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{//move to the end of a file[Self.writehandle SeekToFileOffset:self.begin +Self.currentlength]; //writes data starting at the current moving position (end of file)[Self.writehandle Writedata:data]; //Cumulative LengthSelf.currentlength + =data.length; //Print Download Progress DoubleProgress = (Double) Self.currentlength/(Self.end-self.begin); if(Self.progresshandler) {Self.progresshandler (progress); }}/** 3. When the server's data is accepted, it will be called*/- (void) Connectiondidfinishloading: (Nsurlconnection *) connection{//emptying attribute valuesSelf.currentlength =0; //Close the connection (no longer entering data into the file)[Self.writehandle CloseFile]; Self.writehandle=Nil;}/** * Request error (failure) when called (Request timeout \ off net \ No net, usually refers to client error)*/- (void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{} @end
Design Multi-threaded downloader (use Hmfilemultidownloader to open multiple threads to download a file simultaneously)
A multithreaded downloader downloads only one file
YYFileMultiDownloader.h file
1 " YYFileDownloader.h " 2 3 @interface Yyfilemultidownloader:yyfiledownloader 4 5 @end
YYFILEMULTIDOWNLOADER.M file
#import"YYFileMultiDownloader.h"#import"YYFileSingleDownloader.h"#defineYymaxdownloadcount 4@interface Yyfilemultidownloader () @property (nonatomic, strong) Nsmutablearray*singledownloaders, @property (nonatomic, assign)Long Longtotallength, @end @implementation yyfilemultidownloader- (void) getfilesize{nsmutableurlrequest*request =[Nsmutableurlrequest Requestwithurl:[nsurl URLWithString:self.url]; Request. HttpMethod=@"HEAD"; Nsurlresponse*response =Nil;#warningThe asynchronous request is used here[nsurlconnection sendsynchronousrequest:request returningresponse:&response Error:nil]; Self.totallength=response.expectedcontentlength;}-(Nsmutablearray *) singledownloaders{if(!_singledownloaders) {_singledownloaders=[Nsmutablearray array]; //Get File Size[self getfilesize]; //Number of downloads per path Long LongSize =0; if(self.totallength% Yymaxdownloadcount = =0) {size= Self.totallength/Yymaxdownloadcount; } Else{size= Self.totallength/yymaxdownloadcount +1; } //Create N Downloader for(inti =0; i<yymaxdownloadcount; i++) {Yyfilesingledownloader*singledownloader =[[Yyfilesingledownloader alloc] init]; Singledownloader.url=Self.url; Singledownloader.destpath=Self.destpath; Singledownloader.begin= i *size; Singledownloader.end= singledownloader.begin + Size-1; Singledownloader.progresshandler= ^(Doubleprogress) {NSLog (@"%d---%f", I, progress); }; [_singledownloaders Addobject:singledownloader]; } //Create a temporary file, such as the server file size[[Nsfilemanager Defaultmanager] CreateFileAtPath:self.destPath contents:nil Attributes:nil]; //let the length of Self.destpath file be self.totallengtNsfilehandle *handle =[Nsfilehandle FileHandleForWritingAtPath:self.destPath]; [Handle truncateFileAtOffset:self.totalLength]; } return_singledownloaders;}/** * Start (resume) Download*/- (void) start{[self.singledownloaders makeobjectsperformselector: @selector (start)]; _downloading=YES;}/** * Pause Download*/- (void) pause{[self.singledownloaders makeobjectsperformselector: @selector (pause)]; _downloading=NO;} @end
Supplemental instructions: How to get the size of the file that will be downloaded?
iOS Development Network chapter-Multi-threaded breakpoint Download