使用NSURLSession下载Mp4文件和图片

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *imagView;

@property (nonatomic, strong) NSMutableData *fileData;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

#pragma mark - 点击屏幕开始下载
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    // 下载Mp4文件
    [self downloadMp4File];
    
    // 下载图片
    [self downImage];
}

#pragma mark - 下载Mp4文件
- (void)downloadMp4File{
    //1.确定请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_02.mp4"];
    //2.创建请求对象
    //    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 创建配置文件
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    // 创建Session对象 设置代理 设置线程
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    // 创建下载Task
    //    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    //
    //    }];
    
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
    
    // 开始下载
    [task resume];

}

#pragma mark NSURLSession Delegate
/**
 *  临时路径
 *
 *  @param session      网络Session
 *  @param downloadTask 下载任务
 *  @param location     临时路径
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    // location : 临时文件的路径(下载好的文件)
    NSString *caches = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    // response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致
    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    // 将临时文件剪切或者复制 Caches 文件夹
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    // AtPath : 剪切前的文件路径     // ToPath:剪切后的文件路径
    [mgr moveItemAtPath :location.path toPath:file error : nil];
}

/**
 *  恢复下载的时候调用
 *
 *  @param session            session
 *  @param downloadTask       下载任务
 *  @param fileOffset         已经下载过得流
 *  @param expectedTotalBytes 全部数据
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
    
}

/**
 *  每当下载完(写完)会被调用 可能会被调用多次
 *
 *  @param session                   session
 *  @param downloadTask              下载任务
 *  @param bytesWritten              这次调用写了多少
 *  @param totalBytesWritten         累计写了多少长度到沙盒中了
 *  @param totalBytesExpectedToWrite 文件的总长度
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    // 下载进度
    double progress = (double)totalBytesWritten / totalBytesExpectedToWrite;

    NSLog ( @"下载进度 ---%f", progress);
}

-(void)downImage
{
    
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_02.png"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSData *data = [NSData dataWithContentsOfURL:location];
        dispatch_async(dispatch_get_main_queue(), ^{
           self.imagView.image = [UIImage imageWithData:data];
       });
    }];
    
    [task resume];
}

-(void)dataDonload
{
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_02.png"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    self.imagView.image = [UIImage imageWithData:data];
}
@end```


![NSURLSession.gif](http://upload-images.jianshu.io/upload_images/189984-af5f104232dc0614.gif?imageMogr2/auto-orient/strip)

你可能感兴趣的:(使用NSURLSession下载Mp4文件和图片)