//
// ViewController.m
// NSURLSessionDownloadTask
//
// Created by hq on 16/4/17.
// Copyright © 2016年 hanqing. All rights reserved.
//
#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
@property (weak, nonatomic) IBOutlet UIButton *startBut;
@property (weak, nonatomic) IBOutlet UIProgressView *pro;
- (IBAction)startDownload:(UIButton *)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)startDownload:(UIButton *)sender {
NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
NSString *urlString=@"http://120.25.226.186:32812/resources/videos/minion_01.mp4";
NSURLSessionDownloadTask *task=[session downloadTaskWithURL:[NSURL URLWithString:urlString]];
//恢复下载任务
[task resume];
self.startBut.enabled=NO;
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
NSLog(@"已下载%lld",totalBytesWritten);
NSLog(@"文件总大小%lld",totalBytesExpectedToWrite);
//self.pro.progress=(1.0*totalBytesWritten/totalBytesExpectedToWrite);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//必须放在主线程当中才回更新进度条-----------------------------
self.pro.progress=(1.0*totalBytesWritten/totalBytesExpectedToWrite);
}];
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
//NSLog(@"%@",location);
//下载完成,将文件剪切到我们的cache文件夹当中去
NSString *cachePath=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
NSString *fileName=[cachePath stringByAppendingPathComponent:@"video.mp4"];
NSFileManager *fileManager=[NSFileManager defaultManager];
[fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:fileName] error:nil];
NSLog(@"%@",fileName);
}
//不管下载成功还是失败,都会来到该方法,不过下载失败的话,error有值,下载成功error为null
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
if (error) {
NSLog(@"下载失败了%@",error);
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end