Nsurlsession
1. Steps to use
1> 获得NSURLSession对象2> 利用NSURLSession对象创建对应的任务(Task)3> 开始任务([taskresume])
2. Get Nsurlsession Object
1> [nsurlsession sharedsession ] 2> nsurlsessionconfiguration *cfg = [ Span class= "hljs-variable" >nsurlsessionconfiguration ]; self . session = [nsurlsession sessionwithconfiguration:cfg delegate:self delegatequeue : [nsoperationqueue mainqueue ];
3. Task type
1> Nsurlsessiondatatask
* Purpose: Get\post request for non-file download
NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request];NSURLSessionDataTask *task = [self.session dataTaskWithURL:url];NSURLSessionDataTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {}];
2> Nsurlsessiondownloadtask
* Use: For file download (small file, large file)
NSURLSessionDownloadTask *task = [self.session downloadTaskWithRequest:request];NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:url];NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {}];
Resume Download Instance
#import "ViewController.h" @interface viewcontroller () <nsurlsessiondownloaddelegate, Nsurlsessiondatadelegate>@property(Weak,nonatomic)IboutletUiprogressview *progressview;-(ibaction) Download: (UIButton*) sender;@property(nonatomic,Strong) Nsurlsessiondownloadtask *task;@property(nonatomic,Strong) NSData *resumedata;@property(nonatomic,Strong) Nsurlsession *session;@end @implementation viewcontroller //Lazy loading-(Nsurlsession *) session{if(!_session) {//Get sessionNsurlsessionconfiguration *cfg = [Nsurlsessionconfiguration defaultsessionconfiguration]; Self. Session= [Nsurlsession sessionwithconfiguration:cfg delegate: SelfDelegatequeue:[nsoperationqueue Mainqueue]]; }return_session;} - (ibaction) Download: (UIButton*) Sender {//button state inversionSender. Selected=!sender. isSelected;if( Self. Task==Nil) {//Start (continue) Download if( Self. Resumedata) {//Recovery[ SelfResume]; }Else{//Start[ SelfStart]; } }Else{//Pause[ SelfPause]; }}/** * Start from scratch * /- (void) start{//1. Create a download task Nsurl*url = [Nsurlurlwithstring:@"Http://192.168.1.110:8080/Server/resources"]; Self. Task= [ Self. SessionDownloadtaskwithurl:url];//2. Start a task[ Self. TaskResume];}/** * Resume (CONTINUE) */- (void) resume{//Pass in the last pause to download the returned data, you can resume the download Self. Task= [ Self. SessionDownloadtaskwithresumedata: Self. Resumedata];//Start Task[ Self. TaskResume];//Clear Self. Resumedata=Nil;}/** * Pause * *- (void) pause{__Weaktypeof Self) VC = Self; [ Self. Taskcancelbyproducingresumedata:^ (NSData *resumedata) {///Resumedata: Contains the start location \ Download URL of the continuation downloadVc. Resumedata= Resumedata; Vc. Task=Nil; }];}#pragma mark-nsurlsessiondownloaddelegate- (void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) Downloadtaskdidfinishdownloadingtourl: (Nsurl*) location{NSString*caches = [Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask,YES) Lastobject];//response.suggestedfilename: Recommended file name, generally consistent with server-side file name NSString*file = [Caches stringbyappendingpathcomponent:downloadtask. Response. Suggestedfilename];//Cut temporary files or copy the caches folder Nsfilemanager*mgr = [NsfilemanagerDefaultmanager];//Atpath: File path before clipping //Topath: The file path after clipping[Mgr Moveitematpath:location. PathTopath:file Error:Nil];} - (void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) downloadtask didwritedata: (int64_t) Byteswritten Totalbyteswritten: (int64_t) Totalbyteswrittentotalbytesexpectedtowrite: (int64_t) totalbytesexpectedtowrite{NSLog(@"Get download Progress--%@", [NsthreadCurrentThread]);//Get Download Progress Self. Progressview. Progress= (Double) Totalbyteswritten/totalbytesexpectedtowrite;} - (void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) Downloadtask Didresumeatoffset: (Int64 _t) Fileoffsetexpectedtotalbytes: (int64_t) expectedtotalbytes{}
iOS Development-Nsurlsession implementation of a breakpoint to continue download