"IOS" File download little note

Source: Internet
Author: User

File download is divided into nsurlconnection and nsurlsession Two kinds, the former one has a long history of hate. Using relative trouble, the latter is new and adds some extra functionality.

First, nsurlconnection implementation download

TIPS:

1.whennsurlconnectionwhen downloading,Get theNSDataWrite Filewhen,Dataand noHow much memory to use. (even if the file is large)2.a little bit in the pass. doing is the disk cache.Instead of a memory caching mechanism. 3, understand innsurlconnectionAdd the agent. [ConSetdelegatequeue: [[NsoperationqueueAlloc]Init]]

4.Nsurlresponseit's recorded.URL, Minetype, exceptedcontentlength, Suggestedfilenameand other properties.Useful when downloading.

The following program implements download for tracking download percentage (URLConnection):

#import "XNDownload.h" typedef void (^progressblock) (float percent); @interface Xndownload () < Nsurlconnectiondatadelegate> @property (nonatomic, strong) nsmutabledata *datam;//file path saved in sandbox @property (nonatomic , strong) NSString *cachepath;//file total length @property (nonatomic, assign) long long filelength;//currently downloaded file length @property (nonatomic , assign) long long currentlength;//callback block code @property (nonatomic, copy) progressblock progress; @end @implementation    xndownload-(Nsmutabledata *) datam{if (!_datam) {_datam = [nsmutabledata data]; } return _datam;}        -(void) Downloadwithurl: (nsurl *) URL progress: (void (^) (float)) progress{//0. Record Block Code self.progress = progress; 1.        Request GET Nsurlrequest *request = [Nsurlrequest Requestwithurl:url]; 2.        Connection Nsurlconnection *connection = [nsurlconnection connectionwithrequest:request delegate:self]; Let connection support multi-threading, specify the agent's work queue//nsurlconnection at run time, run loop is not responsible for the specific execution of the listener agent [connection Setdelegatequeue:[[nSoperationqueue alloc] [init]]; 3. Start connection [connection start];} #pragma mark-Proxy method//1. Receives a response from the server, the server finishes the request, and the data is returned to the client-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *)    response{NSLog (@ "%@%lld", Response.suggestedfilename, Response.expectedcontentlength); 1. Saved cache path NSString *cachepath = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES)    Lastobject];    Self.cachepath = [CachePath stringByAppendingPathComponent:response.suggestedFilename]; 2.    Total file Length self.filelength = response.expectedcontentlength; 3.        The currently downloaded file length self.currentlength = 0; emptying data [Self.datam Setdata:nil];} 2. Receive data from server received data-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{//stitching data [Self.datam AP        Penddata:data];        Increase the file length currently downloaded according to the length of data self.currentlength + = Data.length;        float progress = (float) self.currentlength/self.filelength; Determine if the block code is defined if (SELF.Progress) {[[Nsoperationqueue Mainqueue] addoperationwithblock:^{//force run loop to perform an update [[Nsrunloop                        Currentrunloop] Runmode:nsdefaultrunloopmode beforedate:[nsdate Date]];        Self.progress (progress);    }]; }}//3. Complete Receive-(void) connectiondidfinishloading: (nsurlconnection *) connection{NSLog (@ "%s%@", __func__, [Nsthread    CurrentThread]); Write Datam to the cache directory//write data of the sandbox, nsurlconnection the underlying implementation is disk-made cache [Self.datam WriteToFile:self.cachePath atomically:yes];} 4. Error occurred-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{NSLog (@ "%@", error.localizeddescription);} @end

Second, nsurlsession implementation download

Nsurlsession can realize the continuation of the breakpoint, pause the download and other functions.

1.Sessionprovided is themultiple threads are openthe asynchronous Download. 2, download the pausewith thecontinued transmission: (Sessionof theAgentthe methods in)*get aNSDatavariables to save downloaded items.download a task when pausedTaskClear.*continued transmission:will be paused when theDataGiveSessioncontinue to download,and put the previousDataClear.3.TaskBe sure toResumebefore they start executing ..

#import "XNViewController.h" @interface xnviewcontroller () <nsurlsessiondownloaddelegate>//Download the network reply @property ( Nonatomic, strong) nsurlsession *session;//download Task @property (nonatomic, strong) Nsurlsessiondownloadtask *downloadTask;/ /continuation of binary data @property (nonatomic, strong) NSData *resumedata; @end @implementation xnviewcontroller-(nsurlsession *) session{if (!_session) {nsurlsessionconfiguration *config = [Nsurlsessionconfiguration Defaultsessionconfigura        tion];    _session = [nsurlsession sessionwithconfiguration:config delegate:self Delegatequeue:nil]; } return _session;}        -(void) viewdidload{[Super Viewdidload]; [Self downloadFile];}        Pause Download Task-(ibaction) pause{//If the download task does not exist, return directly if (Self.downloadtask = = nil) return; Pause Task (Resumedata in block code is the binary data currently being downloaded)//stop downloading the task and save the data [Self.downloadtask cancelbyproducingresumedata:^ (NSData *re                Sumedata) {self.resumedata = Resumedata; Empty and release the current download task Self.downloadtask = niL }];}    -(Ibaction) resume{//Is there any data to be transmitted?        if (Self.resumedata = = nil) return;    Set up a download task for continuation self.downloadtask = [Self.session downloadTaskWithResumeData:self.resumeData];        [Self.downloadtask resume]; Empty the data from the previous record self.resumedata = nil;} If you use the cache directory in development, be sure to provide a feature, "Clear Cache"!    /** download file */-(void) downloadfile{nsstring *urlstr = @ "http://localhost/teacher complete. rmvb";        URLSTR = [Urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];    Nsurl *url = [Nsurl urlwithstring:urlstr]; (1) Agent & Direct Start either//2.        Start Download Task Self.downloadtask = [Self.session Downloadtaskwithurl:url]; [Self.downloadtask resume];} #pragma mark-Download Agent Method-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) downloadtask Didfinishdownloadingtourl: (Nsurl *) location{NSLog (@ "Complete%@%@", location, [Nsthread CurrentThread]);} /** byteswritten: Number of bytes downloaded totalbyteswritten: bytes downloaded totalbytesexpectedtowrite: Total Download size */-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) Downloadtask Didwritedata: ( int64_t) Byteswritten Totalbyteswritten: (int64_t) Totalbyteswritten totalbytesexpectedtowrite: (int64_t)        totalbytesexpectedtowrite{Float progress = (float) totalbyteswritten/totalbytesexpectedtowrite;    [[Nsoperationqueue Mainqueue] addoperationwithblock:^{///Main thread update progress UI action .... }];} /** Proxy method */-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) downloadtask Didresumeatoffset: (int64_t) Fileoffset expectedtotalbytes: (int64_t) expectedtotalbytes{NSLog (@ "offset:%lld", Fileoffset);} @end

Source:http://blog.csdn.net/xn4545945



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.