iOS network-nsurlsessiondatatask large file offline breakpoint download

Source: Internet
Author: User

What is called offline breakpoint download, is the user download in the Shutdown program reopen can continue to download

The code is implemented as follows:

#import "ViewController.h"@interfaceViewcontroller () <NSURLSessionDataDelegate>//output Stream@property (nonatomic, strong) Nsoutputstream *stream;//Task Object@property (nonatomic, strong) Nsurlsessiondatatask *Datatask;//Total File Size@property (nonatomic, assign) Nsinteger totalsize;//file is currently downloaded size@property (nonatomic, assign) Nsinteger currentsize;//full path of the file@property (nonatomic, strong) NSString *FullPath//Session Object@property (nonatomic, strong) Nsurlsession *session;@end@implementationViewcontroller//Lazy Load Session Object-(Nsurlsession *) session{if(_session = =Nil) {        //3. Creating a Session Object        /*First parameter: configuration information The second parameter: Agent self The third parameter: the queue of the agent method*/nsurlsession*session = [Nsurlsession sessionwithconfiguration:[nsurlsessionconfiguration defaultsessionconfiguration]Delegate: Self delegatequeue:[nsoperationqueue mainqueue]]; _session=session; }    return_session;}//Lazy Load Task-(Nsurlsessiondatatask *) datatask{if(_datatask = =Nil) {        //1. Determine the request pathNSString *urlstr =@"Http://120.25.226.186:32812/resources/videos/minion_01.mp4"; Nsurl*url =[Nsurl Urlwithstring:urlstr]; //2. Create a Request objectNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; NSString*filename =[Urlstr lastpathcomponent]; Nsinteger curentsize=[self getcurrentlength:filename]; //record the currently downloaded sizeSelf.currentsize =curentsize; //set the request header to indicate where the next download startsNSString *range = [NSString stringWithFormat:@"bytes=%zd-", Curentsize]; [Request Setvalue:range Forhttpheaderfield:@"Range"]; //4. Create a taskNsurlsessiondatatask *datatask =[Self.session datataskwithrequest:request]; _datatask=Datatask; }    return_datatask;}-(void) dealloc{//release the session two ways to choose either one[Self.session Invalidateandcancel];//[Self.session Resetwithcompletionhandler:nil];}//Start Download-(Ibaction) Startbtnclick: (ID) sender{[Self.datatask resume];}//Pause Download-(Ibaction) Suspendbtnclick: (ID) sender{[Self.datatask suspend];}//continue to download-(Ibaction) Goonbtnclick: (ID) sender{[Self.datatask resume];}//get current Download Progress-(Nsinteger) Getcurrentlength: (NSString *) filename{Self.fullpath=[[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) Lastobject]    Stringbyappendingpathcomponent:filename]; Nsdictionary*dict =[[Nsfilemanager Defaultmanager] AttributesOfItemAtPath:self.fullPath Error:nil]; NSLog (@"%@", Dict); //get file downloaded sizeNsinteger size = [dict[@"nsfilesize"] IntegerValue]; returnsize;}#pragmaMark-nsurlsessiondatadelegate//1. When a server response is received-(void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) datatask didreceiveresponse: (NSURLResponse *) Response Completionhandler: (void(^) (nsurlsessionresponsedisposition)) completionhandler{//Expectedcontentlength: The size of the data requestedSelf.totalsize = Response.expectedcontentlength +self.currentsize; //Create an output streamNsoutputstream *stream =[[Nsoutputstream Alloc]inittofileatpath:self.fullpath Append:yes]; //Open stream[Stream Open]; Self.stream=stream; //This callback tells the system whether to continue receiving the data that the server returned to US nsurlsessionresponseallow== receiveCompletionhandler (Nsurlsessionresponseallow);}//2. Called when the server returns data, it will be called multiple times-(void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) datatask didreceivedata: (NSData *) data{NSLog (@"didreceivedata---%zd", data.length);    [Self.stream write:data.bytes maxLength:data.length]; Self.currentsize+=data.length; //Print Download ProgressNSLog (@"%f",1.0* Self.currentsize/self.totalsize);}//3. Call at the end of the request (Success | failed), if failed then error has value-(void) Urlsession: (Nsurlsession *) session Task: (Nsurlsessiontask *) Task Didcompletewitherror: (Nserror *) error{NSLog (@"didcompletewitherror---%@", [Nsthread CurrentThread]); //Close the stream[Self.stream Close]; Self.stream=Nil;}@end

iOS network-nsurlsessiondatatask large file offline breakpoint download

Related Article

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.