Implementation Focus:
- Nsurlsessiondatatask to set the request header, get the length of the file downloaded from the path (the file has not been downloaded, the length is 0). Set the requested range by this length
- When the request is received key: file name (MD5 encrypted Url,url guarantees the file name is unique) Value: The length of the file has been downloaded. Save to plist file for easy evaluation of downloaded files
- Write files with Nsoutupstream
- In the agent method of the task completion, the Nsoutupstream is closed and emptied, the corresponding task is emptied, and the corresponding session is emptied.
The code is as follows:
1 #import "ViewController.h"2 #import "nsstring+hash.h"3 4 //Download the URL of the file5 #defineChaosfileurl @ "http://120.25.226.186:32812/resources/videos/minion_01.mp4 "6 7 //based on the file's unique URL MD5 value as the filename8 #defineChaosfilename chaosfileurl.md5string9 Ten //plist file to store the total length of file key: MD5 value of File name value: Total length of files One #defineChaosdownloadfilesplist [[Nssearchpathfordirectoriesindomains (Nscachesdirectory, NSUserDomainMask, YES) lastObject ] stringbyappendingpathcomponent:@ "Downloadfiles.plist"] A - //full path of the downloaded file - #defineChaosfilefullpath [[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) LastObject] Stringbyappendingpathcomponent:chaosfilename] the - //the length of the file that has been downloaded - #defineChaosdownloadlength [[[Nsfilemanager Defaultmanager] Attributesofitematpath:chaosfilefullpath error:nil][@ " Nsfilesize "] IntegerValue] - + @interfaceViewcontroller () <NSURLSessionDataDelegate> - + /** Stream*/ A@property (nonatomic,strong) Nsoutputstream *stream; at - /** Session*/ -@property (nonatomic,strong) nsurlsession *session; - - /** Task*/ -@property (nonatomic,strong) Nsurlsessiondatatask *task; in - /** Totallength*/ to @property (nonatomic,assign) Nsinteger totallength; + - /** Downloadlength*/ the @property (nonatomic,assign) Nsinteger downloadlength; * $ @endPanax Notoginseng - @implementationViewcontroller the +-(Nsurlsession *) Session A { the if(_session = =Nil) { + -_session = [Nsurlsession sessionwithconfiguration:[nsurlsessionconfiguration defaultsessionconfiguration]Delegate: Self Delegatequeue:[[nsoperationqueue alloc] [init]]; $ } $ - return_session; - } the --(Nsurlsessiondatatask *) TaskWuyi { the if(_task = =Nil) { - Wu //Get total file length -Nsinteger totallength =[[Nsdictionary Dictionarywithcontentsoffile:chaosdownloadfilesplist][chaosfilename] integerValue]; About //request the same file, determine the length of the downloaded file, if you have not downloaded this file, totallength = 0 $ if(totallength && Chaosdownloadlength = =totallength) { -NSLog (@"The file has already been downloaded."); - returnNil; - } A +Nsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:[nsurl urlwithstring:chaosfileurl]; the - //set the request header-range from where to start the request data format: bytes=***-*** (from the specified start to the specified end) or: bytes=***-(from the specified position to the end) $NSString *range = [NSString stringWithFormat:@"bytes=%zd-", chaosdownloadlength]; the the[Request Setvalue:range Forhttpheaderfield:@"Range"]; the the_task =[Self.session datataskwithrequest:request]; - in } the return_task; the } About the //Start the-(Ibaction) Startclick: (ID) Sender { the + [Self.task resume]; - } the //PauseBayi-(Ibaction) Pauseclick: (ID) Sender { the the [Self.task suspend]; - } - the- (void) Viewdidload { the [Super Viewdidload]; the } the - #pragmaMark-<NSURLSessionDataDelegate> the /** the * Called when a response is received the */94- (void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) Datatask Didreceiveresponse: ( Nshttpurlresponse *) Response Completionhandler: (void(^) (nsurlsessionresponsedisposition)) Completionhandler the { the //call Blcok in order to receive the data the Completionhandler (nsurlsessionresponseallow);98 //Initialize Stream AboutSelf.stream =[Nsoutputstream Outputstreamtofileatpath:chaosfilefullpath append:yes]; - [Self.stream Open];101 102 //Get total file length103Self.totallength = [response.allheaderfields[@"Content-length"] IntegerValue] +chaosdownloadlength;104 the //received the server response time to store the total length of the file to plist, the implementation of multi-file download, first remove the dictionary, the dictionary assignment to the last write. 106 //Error procedure: Write directly to the file, will overwrite all the original information with this write information107Nsmutabledictionary *dict =[Nsmutabledictionary dictionarywithcontentsoffile:chaosdownloadfilesplist];108 //the dictionary may be empty109 if(Dict = = nil) Dict =[Nsmutabledictionary dictionary]; the //Write File111Dict[chaosfilename] =@ (self.totallength); the [Dict writetofile:chaosdownloadfilesplist atomically:yes];113 } the the /** the * Called when receiving data from the server-it is possible to call multiple times117 */118- (void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) datatask didreceivedata: (NSData *) Data119 { - //Write Data121 [self.stream write:[data bytes] maxLength:data.length];122 //get the length that has been downloaded123Self.downloadlength =chaosdownloadlength;124 //Calculate Progress theNSLog (@"%f",1.0* Self.downloadlength/self.totallength);126 }127 - /**129 * Called when the task is completed the */131- (void) Urlsession: (Nsurlsession *) session Task: (Nsurlsessiontask *) Task Didcompletewitherror: (Nserror *) Error the {133NSLog (@"----Finish");134 [Self.stream close];135Self.stream =Nil;136 137 //a task corresponding to a file, run out of empty138Self.task =Nil;139 } $ @end
iOS Edge Learning--nsurlsessiondatatask Implementation of file real breakpoint continuation