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

Source: Internet
Author: User

Web request technology in iOS development is already a must-have technology for mobile apps, and file transfer is the focus in the network. Network File transfer to the mobile client is mainly divided into file upload and download. As a developer, you can divide files into small files and large files from a technical perspective. Small files because the size of the file is small, resulting in less time to transfer, so it is less likely to affect the user experience, more technology available. Large files Because of large file size resulting in long transmission time, it is necessary to consider a variety of user experience, such as to avoid blocking the main thread during uploading the download file to affect the user experience, you need to use to multithreading technology, in order to give user-friendly progress hints, so you need to track the development of data upload and download data changes In order to improve the user experience, it is also necessary to take into account the function of the continuation of the breakpoint, and the large file transfer is easy to keep the data in memory, but also requires the developer to handle the data in memory, and in order to deal with multiple files or compress the data size of the transfer file, we need to use compression and decompression technology. Depending on the needs of the large file transfer will need to use a different solution, but multi-threaded breakpoint continuation is an ideal transmission of large files in the network scheme.

Small file Download

Small files are more downloaded, the following list of commonly used download methods:

1. Direct with NSData + (ID) Datawithcontentsofurl: (nsurl *) URL method; 2. Use Nsurlconnection to send an HTTP request to download 3. Use Nsurlsession to send an HTTP request to download 4. Use afnetworking to send an HTTP request to download 4. If you are downloading images, you can also use Sdweb Image framebest solution for large file download ——— multi-threaded breakpoint Download  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 completed implementation code is as follows:
Yyviewcontroller.m
#import "YYViewController.h"#import "YYFileMultiDownloader.h"@interfaceYyviewcontroller () @property (nonatomic, strong) Yyfilemultidownloader*Filemultidownloader;@end@implementationYyviewcontroller-(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>@interfaceyyfiledownloader: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

#import " YYFileDownloader.h " @implementation Yyfiledownloader @end

The Downloader class inherits from the Yyfiledownloader class

YYFileSingDownloader.h file

  #import  "     @interface   Yyfilesingledownloader:yyfiledownloader  /*  * * Start position  */  @property (nonatomic, assign)  long  long   begin;  /*  * * End Position  */  @property (nonatomic, assign)  long  long   end;   @end  

YYFILESINGDOWNLOADER.M file

#import "YYFileSingleDownloader.h"@interfaceYyfilesingledownloader () <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@implementationYyfilesingledownloader-(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

#import " YYFileDownloader.h " @interface  @end

YYFILEMULTIDOWNLOADER.M file

#import "YYFileMultiDownloader.h"#import "YYFileSingleDownloader.h"#defineYymaxdownloadcount 4@interfaceYyfilemultidownloader () @property (nonatomic, strong) Nsmutablearray*singledownloaders, @property (nonatomic, assign)Long Longtotallength;@end@implementationYyfilemultidownloader- (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?

Reference article: http://www.cnblogs.com/wendingding/p/3947550.html

iOS Development Network request-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.