Use downloadTask in the NSURLSession

1. downloadTask picture download

Pros: Simple

Disadvantages: can not monitor the progress of the download

Code Example:

    * = URL NSURL [NSURL URLWithString: @ " http://pic1.win4000.com/pic/b/03/21691230681.jpg " ]; 
    NSURLRequest * Request = [NSURLRequest requestWithURL: URL]; 
    
    NSURLSession * = the session [NSURLSession sharedSession ]; 
    NSURLSessionDownloadTask * downloadTask = [the session downloadTaskWithRequest: Request CompletionHandler: ^ (* _Nullable NSURL LOCATION, NSURLResponse * _Nullable the Response, NSError * _Nullable error) {
        // default data is written to disk: tmp / ... could be removed at any time 
        NSLog ( @ " LOCATION =% @ " , LOCATION); 
        
        // transfer file 
        NSString * cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)  lastObject];
        NSString *filePath = [cache stringByAppendingPathComponent:response.suggestedFilename];
        NSLog(@"filePath = %@",filePath);
        NSURL *toURL = [NSURL fileURLWithPath:filePath];
        [[NSFileManager defaultManager] moveItemAtURL:location toURL:toURL error:nil];
    }];
    [downloadTask resume];

 

2.downloadTask download large files

Pros: it has solved the problem of soaring memory

Cons: can not be achieved breakpoint download function

code show as below:

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>

@property (nonatomic,strong) NSURLSession *session;
@property (nonatomic,strong) NSURLSessionDownloadTask *downloadTask;
@property (nonatomic,strong) NSData *resumeData ;

@end

@implementation ViewController

- (IBAction)startClick:(id)sender {
    
    [self.downloadTask resume];
}

- (IBAction)suspendClick:(id)sender {
    [self.downloadTask suspend];
}

- (IBAction)cancleClick:(id)sender {
    //Method of cancel, the operation can not recover
 //     [self.downloadTask cancel]; 
    
    // cancellation, the cancel operation can restore
     // resumeDta may be used to download data recovery 
    [self.downloadTask cancelByProducingResumeData: ^ (* NSData _Nullable resumeData) {
         // data not been downloaded sandbox data 
        self.resumeData = resumeData; 
    }]; 
    
    self.downloadTask = nil; 
}

 - (IBAction) resumeClick: (ID) SENDER {
     // when resume the download, it is determined whether or not It can be used to recover the data downloaded, if then create a new request based on the data network 
    IF (self.resumeData) {
         // cancel and then recover, at the time of recovery, the need to re-create 
        self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
    }
    [self.downloadTask resume];
}

- (NSURLSession *)session {
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

- (NSURLSessionDownloadTask *)downloadTask {
    if (!_downloadTask) {
        NSURL *url = [NSURL URLWithString:@"http://meiye-mbs.oss-cn-shenzhen.aliyuncs.com/mbsFiles/0e3d0e4a0d5d4da5963e9e7617e8de101565841097849.mp4 " ]; 
        NSURLRequest * Request = [NSURLRequest requestWithURL: URL]; 
        _downloadTask = [self.session downloadTaskWithRequest: Request]; 
    } 
    return _downloadTask; 
} 

#pragma Mark - agents
 // 01 write data when the call 
/ * * 
 bytesWritten: the size of the data written 
 totalBytesWritten: the total size of the write data 
 totalBytesExpectedToWrite: the total size of the file 
 * / 
- ( void ) URLSession: (NSURLSession *) session downloadTask: ( NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    NSLog(@"111111=%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}

//02 下载完成的时候调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    //转移文件
    NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)  lastObject];
    NSString *filePath =[Cache stringByAppendingPathComponent: downloadTask.response.suggestedFilename]; 
    NSLog ( @ " filePath =% @ " , filePath); 
    NSURL * the toURL = [NSURL fileURLWithPath: filePath]; 
    [[defaultManager the NSFileManager] moveItemAtURL: the toURL LOCATION: the toURL error: nil] ; 
} 

// 03 end of the entire request, or when the failure to call 
- ( void ) URLSession: (NSURLSession *) Task the session: (NSURLSessionTask *) Task didCompleteWithError: (NSError * ) error { 
    NSLog ( @ " end " ); 
} 
@end

 

Guess you like

Origin www.cnblogs.com/lyz0925/p/11599726.html
use
use