One, the traditional way to download files
-(void) Downloaderwithurl: (Nsurl *) url{ nsurlrequest *request = [Nsurlrequest requestwithurl:url]; [Nsurlconnection sendasynchronousrequest:request Queue:[[nsoperationqueue alloc] init] completionhandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) { if (!connectionerror) { Nshttpurlresponse *urlresponse = (Nshttpurlresponse *) response; if (Urlresponse.statuscode = = | | urlresponse.statuscode = = 304) { [data writetofile:@]/users/gxiangzi/ Desktop/a.mp4 "Atomically:yes"; NSLog (@ "OK"); } } else { NSLog (@ "error"); } }];}
But there are drawbacks to this approach :
1> not be able to track the progress of the download, it is not possible to visually display the download progress
2> file download, will be downloaded into memory, resulting in memory > required file size, resulting in a program crash and other phenomena (can see the cost of memory)
Second, the agent of the way to download the program (nsurlconnectiondownloaddelegate)
#import "GXDownloader.h" @interface gxdownloader () <NSURLConnectionDownloadDelegate> @end @implementation gxdownloader-(void) Downloaderwithurl: (nsurl*) url{nsurlrequest* request = [Nsurlrequest Requestwithurl:url]; [[Nsurlconnection alloc] initwithrequest:request delegate:self];} #pragma mark-nsurlconnectiondownloaddelegate/** Byteswritten: Indicates the number of data bytes downloaded Totalbyteswritten: Total number of bytes downloaded Expectedtotalbytes: Expected total number of bytes */-(void) connection: (nsurlconnection*) connection didwritedata: (Long Long) Byteswritten Totalbyteswritten: (Long Long) Totalbyteswritten expectedtotalbytes: (Long Long) expectedtotalbytes{float progress = ( float) totalbyteswritten/expectedtotalbytes; NSLog (@ "%f", Progress);} /** * @param connection * @param totalbyteswritten: Total number of bytes downloaded * @param expectedtotalbytes: expected total bytes */-(void) Connect Iondidresumedownloading: (nsurlconnection*) connection Totalbyteswritten: (Long Long) Totalbyteswritten Expectedtotalbytes: (Long Long) expectedtotalbytes{}/** * @param connection * @param destinationurl: Downloaded destination path */-(void) connectiondidfinishdownloading: (nsurlconnection*) connection Destinationurl: (nsurl*) destinationurl{NSLog (@ "%@", Destinationurl);}
Advantages:
1> this way can track the progress of file download;
2> can also solve the problem of excessive memory consumption
Cons: This ah download file does not, that is, although you show that the download is complete, but you can not find the file locally ------no eggs
Three, the third Way--agent (Nsurlconnectiondatadelegate)
gxdownloader.m//02-Download////Created by Gxiangzi on 15/8/21.//Copyright (c) 2015 Hqu. All rights reserved.//#import "GXDownloader.h" @interface Gxdownloader () <nsurlconnectiondatadelegate>// Total length of File @property (nonatomic, assign) long long expectedcontentlength;//has accepted the length of the file @property (nonatomic, assign) long long receivedcontentlength;//The total length of the file that has been received @property (nonatomic, strong) nsmutabledata* Receiveddata; @end @implementation gxdownloader-(void) Downloaderwithurl: (nsurl*) url{nsurlrequest* request = [Nsurlrequest Requestwithurl:url]; [[Nsurlconnection alloc] initwithrequest:request delegate:self];} #pragma mark-nsurlconnectiondatadelegate/** * has received a response header */-(void) connection: (nsurlconnection*) connection Didreceiveresponse: (nsurlresponse*) response{self.expectedcontentlength = response.expectedcontentlength;} /** * file is accepted at a point is used */-(void) connection: (nsurlconnection*) connection didreceivedata: (nsdata*) data{//splicing binary data [ Self.receiveddata Appenddata:data]; Stitching length self.receivedcontentlength + = Data.length; float progress = (float) self.receivedcontentlength/self.expectedcontentlength; NSLog (@ "Download progress:%.2f", progress); }/** * Download error when calling */-(void) connection: (nsurlconnection*) connection didfailwitherror: (nserror*) error{}/** * Call when downloading is complete */-(void) connectiondidfinishloading: (nsurlconnection*) connection{NSLog (@ "Download complete"); IOS file path, can only speak software operation data placed in the sandbox nsstring *path = [Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject]; NSString *filename = [path stringbyappendingpathcomponent:@ "Love.mp4"]; NSLog (@ "%@", fileName); [Self.receiveddata Writetofile:filename Atomically:yes]; } #pragma mark-lazy load-(nsmutabledata*) receiveddata{if (!_receiveddata) {_receiveddata = [nsmutabledata data]; } return _receiveddata;} @end
Advantages:
1> can detect the progress of the problem
The file can exist in the path to the 2> file written
Disadvantages:
Too much memory occupied
To solve the above problem: introduced Nshandle and nsoutputstream------The next point to write the file a little
Iv. Use of Nshandle
gxdownloader.m//02-Download////Created by Gxiangzi on 15/8/21.//Copyright (c) 2015 Hqu. All rights reserved.//#import "GXDownloader.h" @interface Gxdownloader () <nsurlconnectiondatadelegate>// Total length of File @property (nonatomic, assign) long long expectedcontentlength;//has accepted the length of the file @property (nonatomic, assign) long long receivedcontentlength; @end @implementation gxdownloader-(void) Downloaderwithurl: (nsurl*) url{NSURLRequest* Request = [Nsurlrequest Requestwithurl:url]; [[Nsurlconnection alloc] initwithrequest:request delegate:self];} #pragma mark-nsurlconnectiondatadelegate/** * has received a response header */-(void) connection: (nsurlconnection*) connection Didreceiveresponse: (nsurlresponse*) response{self.expectedcontentlength = response.expectedcontentlength;} /** * file is accepted at a point is used */-(void) connection: (nsurlconnection*) connection didreceivedata: (nsdata*) data{//Stitching length Self.re Ceivedcontentlength + = Data.length; float progress = (float) self.receivedcontentlength/self.expectedcontenTlength; NSLog (@ "%f", progress); nsstring* path = @ "/users/gxiangzi/desktop/a.mp4"; nsfilehandle* handle = [Nsfilehandle Filehandleforwritingatpath:path]; If handle does not help us create the file if (handle = = nil) {[Data writetofile:path atomically:yes]; } else {//Let offset point to the end of the file and append data at the end [handle seektoendoffile]; Write input [handle writedata:data]; Off (wait for file download to finish close better) [Handle closefile]; }/** * Call */-(void) connectiondidfinishloading when the download is complete: (nsurlconnection*) connection{NSLog (@ "downloads completed");} @end
Principle: Download a bit of data to write a little data
Effect: Able to occupy very little memory
V. Use of Nsoutputstream
gxdownloader.m//02-Download////Created by Gxiangzi on 15/8/21.//Copyright (c) 2015 Hqu. All rights reserved.//#import "GXDownloader.h" @interface Gxdownloader () <nsurlconnectiondatadelegate>// Total length of File @property (nonatomic, assign) long long expectedcontentlength;//has accepted the length of the file @property (nonatomic, assign) long long Receivedcontentlength; @property (nonatomic, strong) nsoutputstream* stream; @end @implementation gxdownloader-(void) Downloaderwithurl: (nsurl*) url{nsurlrequest* request = [Nsurlrequest Requestwithurl:url]; [[Nsurlconnection alloc] initwithrequest:request delegate:self];} #pragma mark-nsurlconnectiondatadelegate/** * has received a response header */-(void) connection: (nsurlconnection*) connection Didreceiveresponse: (nsurlresponse*) response{self.expectedcontentlength = response.expectedcontentlength; nsstring* path = @ "/users/gxiangzi/desktop/a.mp4"; Note Here the URL is local path//front plus file://invalid//only use [Nsurl Fileurlwithpath:path] Self.stream = [Nsoutputstream outputStreamwithurl:[nsurl Fileurlwithpath:path] Append:yes]; [Self.stream Open]; }/** * file is accepted at a point is used */-(void) connection: (nsurlconnection*) connection didreceivedata: (nsdata*) data{//Stitching length SELF.R Eceivedcontentlength + = Data.length; float progress = (float) self.receivedcontentlength/self.expectedcontentlength; NSLog (@ "%f", progress); [Self.stream write:data.bytes maxLength:data.length];} /** * */-(void) connectiondidfinishloading: (nsurlconnection*) connection{NSLog (@ "Download done") when download is complete; [Self.stream close];} -(Nsoutputstream *) stream{if (_stream = = nil) {_stream = [[Nsoutputstream alloc] init]; } return _stream;} @end
Download for "Finishing" iOS development