NSURLSessionDownloadTask 加MBProgressHUD的简单应用

新建工具类继承于NSObject

.h中

//正在下载
typedef void(^downLoading)(long long bytesWritten,float progress);
//下载完成之后要走的方法
typedef void(^comlated)(NSString *filepath);


@interface downLoad : NSObject
//重写初始化方法
- (instancetype)initWithUrl:(NSString *)url;
//开始下载
- (void)startDownload;
//暂停下载
- (void)stopDownload;
// 下载/下载完成
- (void)downloading:(downLoading)downloading didFinashed:(comlated)didFinashed;


.m 中

@interface downLoad ()

@property (nonatomic ,strong)NSURLSession *session;

@property (nonatomic ,strong)NSURLSessionDownloadTask *task;
//正在下载
@property (nonatomic ,copy)downLoading downloading;
//下载完成
@property (nonatomic ,copy)comlated comlated;

@end

@implementation downLoad

- (NSURLSession *)session{
    //懒加载
    if (!_session) {
        
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    }
    
    return _session;
}
//自定义初始化方法
- (instancetype)initWithUrl:(NSString *)url{
    
    self = [super init];
    if (self) {
        //创建一个下载任务
        self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:url]];
        
    }
    return self;
}




//开始下载
- (void)startDownload{
    [self.task resume];
}


//暂停下载
- (void)stopDownload{
    [self.task suspend];
}

//正在下载

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    
    if (self.comlated) {
        //设置progress的格式 0~1
        self.downloading(bytesWritten,totalBytesWritten/(float)totalBytesExpectedToWrite);
    }
    
}

//下载完成之后
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    //要存放下载文件的路径
    NSString *filepath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    //拼接文件的名字,名字是服务器给的
    NSString *filename = downloadTask.response.suggestedFilename;
    
    filepath = [filepath stringByAppendingPathComponent:filename];
    //文件管理器,将临时文件移动到缓存文件中
    [[NSFileManager defaultManager]moveItemAtPath:location.path toPath:filepath error:nil];
    if (self.comlated) {
        self.comlated(filepath);
    }
    
    
    
}

//下载完成之后要走的方法
- (void)downloading:(downLoading)downloading didFinashed:(comlated)didFinashed{
    
    self.downloading = downloading;
    
    self.comlated = didFinashed;
    
}

viewController.m中

属性、头文件
@interface ViewController ()
//设置MBProgressHUD 属性
@property (nonatomic ,strong)MBProgressHUD *hub;
//downLoad 属性
@property (nonatomic ,strong)downLoad *mydownload;

@property (weak, nonatomic) IBOutlet UIView *blueView;
//用来传值
@property (nonatomic )float progresss;

懒加载部分
//懒加载
- (MBProgressHUD *)hub {
    
    if (!_hub) {
        _hub = [[MBProgressHUD alloc]initWithView:self.view];
        [self.blueView addSubview:_hub];
    }
    return _hub;
}


- (downLoad *)mydownload{
    if (!_mydownload) {
        _mydownload = [[downLoad alloc]initWithUrl:kdownloadUrl];
    }
    return _mydownload;
}

viewDidLoad 中
 //下载
    [self download];

点击事件
#开始
- (IBAction)startDownloadAction:(UIButton *)sender {
    //开始下载
    [self.mydownload startDownload];
    
    //设置任务进行时需要做的事情
    self.hub.labelText = @"请稍等";
    
    //设置提示框样,MBProgressHUDModeDeterminate是个枚举值
    self.hub.mode = MBProgressHUDModeDeterminate;
    
    //设置任务进行时的动画
    [self.hub showAnimated:YES whileExecutingBlock:^{

        while (self.progresss < 1.0f) {

            self.hub.progress = self.progresss;
            usleep(50000);
        }
        
    }completionBlock:^{
        //任务完成之后需要做的事情
        
        [self.hub removeFromSuperViewOnHide];
        self.hub = nil;
        self.hub.labelText = @"下载成功";
        //文本提示框
        self.hub.mode = MBProgressHUDModeCustomView;
        
        [self.hub showAnimated:YES whileExecutingBlock:^{
            //设置文本提示框消失的时间(单位为秒)
            sleep(2);
        } completionBlock:^{
            //当文本框消失后把它移除
            [self.hub removeFromSuperViewOnHide];
            self.hub = nil;
        }];
    }];
    
    
}


//这里面是下载中和下载完要走的方法
- (void)download{
   [self.mydownload downloading:^(long long bytesWritten, float progress) {
       self.progresss = progress;
       NSLog(@"%f",progress);
   } didFinashed:^(NSString *filepath) {
       NSLog(@"%@",filepath);
   }];
   
    
}

#暂停
- (IBAction)suspendDownloadAction:(UIButton *)sender {
    //暂停下载
    [self.mydownload stopDownload];
    
    
}

storyboard 中

NSURLSessionDownloadTask 加MBProgressHUD的简单应用_第1张图片
屏幕快照 2016-06-25 下午11.33.12.png

运行

123.gif

你可能感兴趣的:(NSURLSessionDownloadTask 加MBProgressHUD的简单应用)