iOS Development elearning 11: Nsurlsessiondatatask offline Breakpoint Download (breakpoint continuation)

Source: Internet
Author: User

#import "ViewController.h"#defineFileName @ "121212.mp4"@interfaceViewcontroller () <NSURLSessionDataDelegate>@property (Weak, nonatomic) Iboutlet Uiprogressview*Proessview;/** Receive response body information*/@property (nonatomic, strong) Nsfilehandle*handle; @property (nonatomic, assign) Nsinteger totalsize; @property (nonatomic, assign) Nsinteger currentsize;@ Property (Nonatomic, strong) NSString*FullPath, @property (nonatomic, strong) Nsurlsessiondatatask*Datatask, @property (nonatomic, strong) Nsurlsession*session;@end@implementationViewcontroller-(void) viewdidload{[Super Viewdidload]; //1. Read the total size of the saved file data, 0//2. Get the size of the currently downloaded data//3. Calculate Progress Information    }-(NSString *) fullpath{if(_fullpath = =Nil) {                //get file Full path_fullpath =[[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) Lastobject]    Stringbyappendingpathcomponent:filename]; }    return_fullpath;}-(Nsurlsession *) session{if(_session = =Nil) {        //3. Create the Session object, set the proxy        /*First parameter: configuration information [nsurlsessionconfiguration defaultsessionconfiguration] Second parameter: Agent third parameter: Sets the Agent method on which thread Called in*/_session= [Nsurlsession sessionwithconfiguration:[nsurlsessionconfiguration defaultsessionconfiguration]Delegate: Self delegatequeue:[nsoperationqueue mainqueue]]; }    return_session;}-(Nsurlsessiondatatask *) datatask{if(_datatask = =Nil) {        //1.urlNsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/resources/videos/minion_01.mp4"]; //2. Create a Request objectNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; //3 Set the request header information to tell the server to request that part of the dataSelf.currentsize =[self getfilesize]; NSString*range = [NSString stringWithFormat:@"bytes=%zd-", Self.currentsize]; [Request Setvalue:range Forhttpheaderfield:@"Range"]; //4. Create a task_datatask =[Self.session datataskwithrequest:request]; }    return_datatask;}-(Nsinteger) getfilesize{//gets the data size for the specified file path corresponding fileNsdictionary *fileinfodict =[[Nsfilemanager Defaultmanager]attributesofitematpath:self.fullpath Error:nil]; NSLog (@"%@", fileinfodict); Nsinteger currentsize= [fileinfodict[@"nsfilesize"] IntegerValue]; returncurrentsize;}-(Ibaction) Startbtnclick: (ID) sender{[Self.datatask resume];}-(Ibaction) Suspendbtnclick: (ID) sender{NSLog (@"_________________________suspend"); [Self.datatask suspend];}//Note: Datatask cancellation is not recoverable-(Ibaction) Cancelbtnclick: (ID) sender{NSLog (@"_________________________cancel");    [Self.datatask Cancel]; Self.datatask=Nil;}-(Ibaction) Goonbtnclick: (ID) sender{NSLog (@"_________________________resume"); [Self.datatask resume];}#pragmaMark----------------------#pragmaMark Nsurlsessiondatadelegate/** 1. Receive a response to the server it cancels the request by default * * @param Session Object * @param datatask Request Task * @param response Response header information * @param Completionhandler callback to the system*/-(void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) datatask didreceiveresponse: (NSURLResponse *) Response Completionhandler: (void(^) (nsurlsessionresponsedisposition)) completionhandler{//get the total size of the file//expectedcontentlength data size for this requestSelf.totalsize = Response.expectedcontentlength +self.currentsize; if(Self.currentsize = =0) {        //Create an empty file[[Nsfilemanager Defaultmanager]createfileatpath:self.fullpath Contents:nil Attributes:nil]; }    //To create a file handleSelf.handle =[Nsfilehandle FileHandleForWritingAtPath:self.fullPath]; //Move Pointer[Self.handle Seektoendoffile]; /*nsurlsessionresponsecancel = 0, cancel default Nsurlsessionresponseallow = 1, receive Nsurlsessionresponsebecomedownload = 2, becomes the download task Nsurlsessionresponsebecomestream into stream*/Completionhandler (Nsurlsessionresponseallow);}/** * receive data calls returned by the server multiple times * * @param Session Object * @param datatask Request task * @param data Data for this download*/-(void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) datatask didreceivedata: (NSData *) data{//writing data to a file[Self.handle Writedata:data]; //Calculate the download progress of a fileSelf.currentsize + =data.length; NSLog (@"%f",1.0* Self.currentsize/self.totalsize); Self.proessView.progress=1.0* Self.currentsize/self.totalsize;}/** * when the request ends or fails, call * * @param Session Object * @param datatask Request task * @param error Information*/-(void) Urlsession: (Nsurlsession *) session Task: (Nsurlsessiontask *) Task Didcompletewitherror: (Nserror *) error{NSLog (@"%@", Self.fullpath); //Close file handle[Self.handle CloseFile]; Self.handle=Nil;}-(void) dealloc{//Cleanup Work//finishtasksandinvalidate[Self.session invalidateandcancel];}@end

# # # # # # #6 use Nsurlsessiondatatask to implement large file offline breakpoint download (complete)

(1) about the use of Nsoutputstream

"' OBJC

1. Create an input stream, append data to the file's butt

Writes the data to the specified file address, and if the current file does not exist, it is automatically created

Nsoutputstream *stream = [[Nsoutputstream alloc]initwithurl:[nsurl fileurlwithpath:[self FullPath]] Append:YES];

2. Open stream

[Stream Open];

3. Write stream data

[Stream write:data.bytes maxLength:data.length];

4. You should close the stream when it is not needed

[Stream Close];

```

(2) Settings for the network request header (you can set a part of the request download file)

"' OBJC

1. Set the Request object

1.1 Create Request Path

Nsurl *url = [Nsurl urlwithstring:@ "Http://120.25.226.186:32812/resources/videos/minion_01.mp4"];

1.2 Creating a Mutable Request object

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

1.3 Get the remaining data size of the current file

Self.currentcontentlength = [self FileSize];

1.4 Tell the server where to start downloading file data

NSString *range = [NSString stringwithformat:@ "bytes=%zd-", self.currentcontentlength];

NSLog (@ "%@", range);

1.5 Setting the request header

[Request Setvalue:range forhttpheaderfield:@ "range"];

```

(3) Release of Nsurlsession objects

"' OBJC

-(void) dealloc

{

The session should be released at the end of the day to avoid memory leaks.

Nsurlsession after the agent has been set up, you need to call the session's Invalidateandcancel or Resetwithcompletionhandler at the end (e.g. when the controller is destroyed), so that there is no memory leak

[Self.session Invalidateandcancel];

[Self.session resetwithcompletionhandler:^{

NSLog (@ "Release---");

}];

}

```

(4) Optimization section

01 Real-time updates on file download progress

02 Independence and extraction of methods

---

iOS Development elearning 11: Nsurlsessiondatatask offline Breakpoint Download (breakpoint continuation)

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.