断点续传功能的实现

本文详细介绍了如何使用NSURL系列方法在iOS中实现断点续传功能,包括下载状态和处理Block的定义、CMDownloadTask类的设计、状态切换、开始、暂停和取消下载的操作,以及通知观察者更新UI的机制。通过一个任务列表单例来管理多个下载任务,支持下载任务的增删查。
摘要由CSDN通过智能技术生成

断点续传功能的实现

项目中需要使用到断点续传的功能,用于群文件共享的下载,本来是打算使用公司原来用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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值