断点续传功能的实现
项目中需要使用到断点续传的功能,用于群文件共享的下载,本来是打算使用公司原来用C++写的下载,但是实在太麻烦、不方便,几经思考,决定自己动手使用NSURL系列方法来实现,现将代码纪录以供将来重复使用。
下载状态和下载处理Block的定义
首先需要定义下载的状态以及接收到数据时留出的回调Block,包括一些宏定义,如下所示:
typedef NS_ENUM(NSUInteger, DownloadStatus) {
DownloadStatusNone, //无状态
DownloadStatusDowloading, //正在下载
DownloadStatusPaused, //暂停下载
DownloadStatusCancelled, //已取消下载
DownloadStatusDownloaded //完成下载
};
typedef void(^DownloadProgressHandler)(CGFloat, CGFloat);
#define DOWNLOAD_FILE_PATH(fileName) [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"ulp/download/%@",(fileName)]]
#define DOWNLOAD_FILE_PATH_WITH_EXTENSION(fileName,fileExtension [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"ulp/download/%@.%@",(fileName),(fileExtension)]]
#define DownloadFailedNotification @"DownloadFailedNotification"
#define DownloadCompleteNotification @"DownloadCompleteNotification"
DownloadProgressHandler主要是留给UI用于更新UIProgressView及其他指示性的文本。
定义下载任务
CMDownloadTask类的定义
类CMDownloadTask表示一个可能处在任何状态的一个下载任务,代码如下所示:
@interface CMDownloadTask : NSObject <NSURLSessionDownloadDelegate> {
DownloadStatus theCurrentStatus;
NSMutableDictionary* observerDict;
}
@property(nonatomic,strong) NSURLSessionDownloadTask* downloadTask;
@property(nonatomic,strong) NSData* resumeData;
@property(nonatomic,copy) NSString* downloadUrl;
@property(nonatomic,copy) NSString* downloadFileName;
@property(nonatomic,strong) NSDate* previousDownloadDate;
-(instancetype)initWithUrl:(NSString*)urlStr downloadFileName:(NSString*)fileName;
-(DownloadStatus)getCurrentStatus;
-(void)changeCurrentStatus:(DownloadStatus)status;
-(void)addObserverWithBlock:(DownloadProgressHandler)downloadHandler WithUrl:(NSStr