#import "ViewController.h"
@interface ViewController ()<NSURLSessionDelegate, NSURLSessionDownloadDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property(nonatomic, strong) NSURLSessionTask *downLoadTask;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:@"http://hc25.aipai.com/user/656/20448656/6167672/card/25033081/card.mp4?l=a"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
self.downLoadTask = [session downloadTaskWithRequest:urlRequest];
}
#pragma mark 开始下载
- (IBAction)startAction:(UIButton *)sender {
[self.downLoadTask resume];
}
#pragma mark 暂停下载
- (IBAction)suspendAction:(UIButton *)sender {
[self.downLoadTask suspend];
}
#pragma mark 恢复下载
- (IBAction)resumeAction:(UIButton *)sender {
[self.downLoadTask resume];
}
#pragma mark 下载完成后调用的方法
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSLog(@"下载存放的临时路径 = %@", location.path);
NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
NSString *imagePath = [cachesPath stringByAppendingString:@"/image.mp4"];
NSFileManager *fileManger = [NSFileManager defaultManager];
[fileManger moveItemAtPath:location.path toPath:imagePath error:nil];
NSLog(@"转存后的路径 = %@", imagePath);
}
-(void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
NSLog(@"速度:%lld kb/s, 已经下载:%lldkb 总大小:%lldkb ", bytesWritten/1024, totalBytesWritten/1024, totalBytesExpectedToWrite/1024);
self.progressView.progress = (double)totalBytesWritten/totalBytesExpectedToWrite;
}