下载管理
DownloadManager.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void(^DownloadProgressBlock)(float progress);
typedef void(^DownloadCompleteBlock)(BOOL success, NSString * _Nullable filePath, NSError * _Nullable error);
@interface DownloadManager : NSObject
- (void)downloadWithUrl:(NSURL *)url toPath:(NSString *)toPath progress:(DownloadProgressBlock)progress complete:(DownloadCompleteBlock)complete;
- (void)cancel;
- (void)suspend;
- (void)resume;
@end
DownloadManager.m
#import "DownloadManager.h"
@interface DownloadManager () <NSURLSessionDelegate>
@property (nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration;
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;
@property (nonatomic, copy) DownloadProgressBlock progress;
@property (nonatomic, copy) DownloadCompleteBlock complete;
@property (nonatomic, strong) NSURL *fileUrl;
@property (nonatomic, strong) NSString *toPath;
@end
@implementation DownloadManager
#define ImageURL @"http://p3.so.qhimg.com/t01bddfda09bdfc39a3.jpg" //test
- (void)downloadWithUrl:(NSURL *)url toPath:(NSString *)toPath progress:(DownloadProgressBlock)progress complete:(DownloadCompleteBlock)complete
{
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
self.sessionConfiguration = sessionConfiguration;
NSURLSession *downloadSession = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
self.session = downloadSession;
//test
// url = [NSURL URLWithString:ImageURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDownloadTask *downloadTask = [downloadSession downloadTaskWithRequest:request];
self.downloadTask = downloadTask;
self.fileUrl = url;
self.toPath = toPath;
self.progress = progress;
self.complete = complete;
[downloadTask resume];
}
- (void)cancel
{
if (self.downloadTask) {
[self.downloadTask cancel];
}
}
- (void)suspend
{
if (self.downloadTask) {
[self.downloadTask suspend];
}
}
- (void)resume
{
if (self.downloadTask) {
[self.downloadTask resume];
}
}
#pragma mark - NSURLSessionDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"app: bytesWritten=%@,totalBytesWritten=%@,totalBytesExpectedToWrite=%@",@(bytesWritten),@(totalBytesWritten),@(totalBytesExpectedToWrite));
float progress = (float)totalBytesWritten/totalBytesExpectedToWrite;
if (self.progress) {
self.progress(progress);
}
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSLog(@"任务下载完成");
if (self.progress) {
self.progress(1.0);
}
//1 拼接文件全路径
if (self.toPath.length) {
if (self.toPath.lastPathComponent.length) {
//do nothing
} else {
self.toPath = [self.toPath stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
}
} else {
//默认下载到/Library/Cache/SavedFiles
NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
NSString *appDir = [cacheDir stringByAppendingPathComponent:@"SavedFiles"];
self.toPath = [appDir stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
}
//2 必须要剪切文件, 因为系统默认会删除
if ([[NSFileManager defaultManager] fileExistsAtPath:self.toPath]) {
[[NSFileManager defaultManager] removeItemAtPath:self.toPath error:nil];
}
//创建文件夹
NSString *dir = [self.toPath stringByDeletingLastPathComponent];
BOOL isDir = YES;
if (![[NSFileManager defaultManager] fileExistsAtPath:dir isDirectory:&isDir]) {
[[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
}
[[NSFileManager defaultManager]moveItemAtURL:location toURL:[NSURL fileURLWithPath:self.toPath] error:nil];
NSLog(@"app: download ok, path:%@", self.toPath);
}
//无论是数据任务还是上传任务执行完之后都会执行该回调
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"整个任务完成");
NSLog(@"app: download complete, error:%@", error);
if (error) {
// check if resume data are available
if ([error.userInfo objectForKey:NSURLSessionDownloadTaskResumeData]) {
NSData *resumeData = [error.userInfo objectForKey:NSURLSessionDownloadTaskResumeData];
//通过之前保存的resumeData,获取断点的NSURLSessionTask,调用resume恢复下载
// self.resumeData = resumeData;
//弹出提示框,如果需要重新下载,则调用[download taskwithResumeData]
}
} else {
//下载完成处理
}
if (self.complete) {
self.complete(error ? NO : YES, error ? nil : self.toPath, error);
}
}
@end
下载调用
SYDownloadManager *manager = [[SYDownloadManager alloc] init];
[manager downloadWithUrl:[NSURL URLWithString:url] toPath:toPath progress:^(float progress) {
//other things
} complete:^(BOOL success, NSString * _Nullable filePath, NSError * _Nullable error) {
if (self.completeCallback) {
NSDictionary *dic = error ? @{
@"code" : @(error.code),
@"success" : @(success),
@"errMsg" : error.userInfo.description ? error.userInfo.description : @""
} : @{
@"success" : @(success),
@"filePath" : filePath,
};
//other things
}
}];