iOS Development Network-Multi-threaded breakpoint download for large files

Source: Internet
Author: User

Http://www.cnblogs.com/wendingding/p/3947550.html

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:

 1 #import "YYViewController.h" 2 #import "YYFileMultiDownloader.h" 3 4 @interface Yyviewcontroller () 5 @property (Nonat Omic, strong) Yyfilemultidownloader *filemultidownloader; 6 @end 7 8 @implementation Yyviewcontroller 9-(Yyfilemultidownloader *) FileMultiDownloader10 {one-if (!_filemultido Wnloader) {_filemultidownloader = [[Yyfilemultidownloader alloc] init];13//files to be downloaded remote URL14 _fi  Lemultidownloader.url = @ "Http://192.168.1.200:8080/MJServer/resources/jre.zip"; 15//Where is the file saved? nsstring *caches = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) lastObject];17 NSString     *filepath = [Caches stringbyappendingpathcomponent:@ "Jre.zip"];18 _filemultidownloader.destpath = filepath;19 }20 return _filemultidownloader;21}22-(void) viewDidLoad24 {+ [super viewdidload];26}28-(void) t Ouchesbegan: (Nsset *) touches withevent: (uievent *) Event30 {Self.filemultidownloaDer start];32}33 @end 

Customizing a base class

YYFileDownloader.h file

1 #import <Foundation/Foundation.h> 2  3 @interface yyfiledownloader:nsobject 4 {5     BOOL _downloading; 6} 7/** 8  * The remote URL (path of the connection server) required to download the file 9  */10 @property (nonatomic, copy) nsstring *url;11/**12  * File storage path (file download to what place)  */14 @property (nonatomic, copy) NSString *destpath;15/**17 * is  downloading (there is no download, only the inside of the Downloader)  */19 @  Property (Nonatomic, readonly, getter = isdownloading) BOOL downloading;20/**22  * used to monitor download progress  */24 @property (nonatomic, copy) void (^progresshandler) (double progress);/**27  * Start (Restore) Download  */29-(void) start;30 31/* *32  * Pause Download  */34-(void) pause;35 @end

YYFILEDOWNLOADER.M file

1 #import "YYFileDownloader.h" 2 3 @implementation YYFileDownloader4 @end

The Downloader class inherits from the Yyfiledownloader class

YYFileSingDownloader.h file

1 #import "YYFileDownloader.h" 2  3 @interface yyfilesingledownloader:yyfiledownloader 4/** 5  *  start position 6
   
    */7 @property (nonatomic, assign) long long begin; 8/** 9  *  End position  */11 @property (nonatomic, assign) long long end; @end
   

YYFILESINGDOWNLOADER.M file

  1 #import "YYFileSingleDownloader.h" 2 @interface yyfilesingledownloader () <NSURLConnectionDataDelegate> 3/**  4 * Connection Object 5 */6 @property (nonatomic, strong) nsurlconnection *conn; 7 8/** 9 * File handle for writing data */One @property (nonatomic, strong) Nsfilehandle *writehandle; 12/** 13 * Length of currently downloaded data */@property (nonatomic, assign) long long currentlength; @end @implementation Yyfilesingledownloader-(Nsfilehandle *) Writehandle (!_writehandle) {_writehandle = [nsfilehandle FileHandleForWritingAtPath:self.destPath]; 26} 27 28/** 29 * Start (Resume) Download */-(void) Start (nsurl) *url = [Nsurl URLWithString:self.url]; 34// The default is GET request nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];  36//Set Request header information PNs nsstring *value = [NSString stringwithformat:@ "Bytes=%lld-%lld", Self.begin + self.currentlength, Self.end]; [Request Setvalue:valueforhttpheaderfield:@ "Range"]; Self.conn = [nsurlconnection connectionwithrequest:request delegate:self]; _downloading = YES;     42} 43 44/** 45 * Pause Download */-(void) pause [self.conn cancel]; self.conn = nil; 51 52 _downloading = NO; #pragma mark-nsurlconnectiondatadelegate Agent Method 57/** 58 * 1. When the response to the server is accepted (connected to the server), the connection is called: (nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) Response 61 {62 63} 64 65/** 66 * 2. 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 69 {70//moved to the tail of file [Self.writehandle SeekToFileOffset:self.begin + self.currentlength]; 72/ /start writing data from the currently moving position (end of file) [Self.writehandle Writedata:data]; 74 75//Cumulative length self.currentlength + = Data.length; 77 78//Print download progress double progress = (double) self.currentlength/(Self.end-self.begin); if (self.progresshandler) {Bayi Self.progresshandler (progress); 82} 83} 84 85/** 86 * 3. When the server's data has been accepted, it will call the * * * (void) connectiondidfinishloading: (nsurlconnection *) connection 89 {90//Empty attribute value lf.currentlength = 0; 92 93//Close connection (no longer input data into file) 94 [Self.writehandle CloseFile]; Self.writehandle = nil; 96} 97 98/** 99 * Request error (failed) call (Request timed out \ off net \ No net, general refer to client Error) */101-(void) connection: (Nsurlconnection *) connection did Failwitherror: (Nserror *) error102 {103 104}105 106 @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 #import "YYFileDownloader.h" 2 3 @interface yyfilemultidownloader:yyfiledownloader4 5 @end

YYFILEMULTIDOWNLOADER.M file

 1 #import "YYFileMultiDownloader.h" 2 #import "YYFileSingleDownloader.h" 3 4 #define YYMAXDOWNLOADCOUNT 4 5 6 @interfac e Yyfilemultidownloader () 7 @property (nonatomic, strong) Nsmutablearray *singledownloaders; 8 @property (nonatomic, assign) long long totallength; 9 @end10 @implementation YYFileMultiDownloader12-(void) GetFilesize14 {nsmutableurlrequest *request = [Nsmut Ableurlrequest Requestwithurl:[nsurl urlwithstring:self.url]];16 request. HttpMethod = @ "HEAD"; nsurlresponse *response = nil;19 #warning here to use asynchronous request [Nsurlconnection Sendsynchrono Usrequest:request returningresponse:&response error:nil];21 self.totallength = response.expectedContentLength; }23-(Nsmutablearray *) singleDownloaders25 {if (!_singledownloaders) {_singledownloaders = [Nsmut]         Ablearray array];28 29//Get file size [self getfilesize];31 32//Download volume per path 33 A long long size = 0;34 if (self.totallenGth% Yymaxdownloadcount = = 0) {size = self.totallength/yymaxdownloadcount;36} else {37 Size = Self.totallength/yymaxdownloadcount + 1;38}39 40//Create n downloader x for (int i = 0 ; i<yymaxdownloadcount; i++) {Yyfilesingledownloader *singledownloader = [[Yyfilesingledownloader alloc] init];43 Singl Edownloader.url = self.url;44 Singledownloader.destpath = self.destpath;45 Singledownloader.begin = i * size;46 singledownloader.end = singledownloader.begin + size-1;47 singledownloader.progres Shandler = ^ (double progress) {NSLog (@ "%d---%f", I, progress);};50 [_single downloaders addobject:singledownloader];51}52 53//Create a temporary file with size such as server file [[Nsfilemanager Defaultmanager] CreateFileAtPath:self.destPath Contents:nil attributes:nil];55 56//Let Self.destpath file longDegree is self.totallengt57 nsfilehandle *handle = [Nsfilehandle filehandleforwritingatpath:self.destpath];58 [Han Dle truncatefileatoffset:self.totallength];59}60 return _singledownloaders;61}62 63/**64 * Start (Resume) Download 65 */66- (void) start67 {self.singledownloaders makeobjectsperformselector: @selector (start)];69 _downloading = YE s;71}72 73/**74 * Pause download */76-(void) pause77 {[Self.singledownloaders makeobjectsperformselector: @selector (Pau SE)];79 _downloading = no;80}81 @end

Supplemental instructions: How to get the size of the file that will be downloaded?

iOS Development Network-Multi-threaded breakpoint download for large files

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.