IOS development-NSURLSession for resumable download
NSURLSession
1. Procedure
1> obtain the NSURLSession object 2> create a Task using the NSURLSession object 3> Start the task ([Task resume])
2. Obtain the NSURLSession object
1> [NSURLSession sharedSession]2> NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
3. Task Type
1> NSURLSessionDataTask
* Purpose: used for non-File Download GET \ POST requests
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
* Purpose: used for downloading files (small files and large files)
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) {}];
Resumable download instance
# Import "ViewController. h" @ interface ViewController ()
@ Property (weak, nonatomic) IBOutlet UIProgressView * 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) {// obtain the session NSURLSessionConfiguration * cfg = [NSURLSessionConfiguration defaultSessionConfiguration]; self. session = [NSURLSession sessionWithConfiguration: cfg delegate: self delegateQueue: [NSOperationQueue mainQueue];} return _ session;}-(IBAction) download :( UIButton *) sender {// reverse sender for button status. selected =! Sender. isSelected; if (self. task = nil) {// start (CONTINUE) download if (self. resumeData) {// restore [self resume];} else {// start [self start];} else {// pause [self pause];} /*** start from scratch */-(void) start {// 1. create a download task NSURL * url = [NSURL URLWithString: @ "http: // 192.168.1.110: 8080/Server/resources"]; self. task = [self. session downloadTaskWithURL: url]; // 2. start task [self. task resume];}/*** resume (CONTINUE) */-(void) resume {// pass in the data returned from the last pause download to resume the download of self. task = [self. session downloadTaskWithResumeData: self. resumeData]; // start the task [self. task resume]; // clear self. resumeData = nil;}/*** pause */-(void) pause {_ weak typeof (self) vc = self; [self. task cancelByProducingResumeData: ^ (NSData * resumeData) {// resumeData: contains the starting position of the download and the url vc of the download. resumeData = resumeData; vc. task = nil ;}] ;}# pragma mark-NSURLSessionDownloadDelegate-(void) URLSession :( NSURLSession *) session downloadTask :( NSURLSessionDownloadTask *) Resume :( NSURL *) location {NSString * caches = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) lastObject]; // response. suggestedFilename: Recommended file name, which is generally the same as the file name on the server. NSString * file = [caches stringByAppendingPathComponent: downloadTask. response. suggestedFilename]; // cut the temporary file or copy the NSFileManager * mgr = [NSFileManager defaultManager] In the Caches folder; // AtPath: the file path before the cut // ToPath: path of the cut file [mgr moveItemAtPath: location. path toPath: file error: nil];}-(void) URLSession :( NSURLSession *) session downloadTask :( 0000*) downloadTask didWriteData :( int64_t) bytesWritten failed :( int64_t) failed :( int64_t) totalBytesExpectedToWrite {NSLog (@ "Get download progress -- % @", [NSThread currentThread]); // get download progress self. progressView. progress = (double) upload/upload;}-(void) URLSession :( NSURLSession *) session downloadTask :( upload *) downloadTask didResumeAtOffset :( int64_t) Upload :( int64_t) expectedTotalBytes {}