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 ()<NSURLSessionDownloadDelegate>

@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 ()<MBProgressHUDDelegate>
//设置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 中

屏幕快照 2016-06-25 下午11.33.12.png

运行

123.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,776评论 0 9
  • 1,NSObject中description属性的意义,它可以重写吗?答案:每当 NSLog(@"")函数中出现 ...
    eightzg阅读 4,192评论 2 19
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,212评论 30 472
  • 原文: iOS应用架构谈 view层的组织和调用方案 iOS应用架构谈 开篇 iOS应用架构谈 网络层设计方案 i...
    难却却阅读 1,278评论 0 7
  • 父类实现深拷贝时,子类如何实现深度拷贝。父类没有实现深拷贝时,子类如何实现深度拷贝。• 深拷贝同浅拷贝的区别:浅拷...
    JonesCxy阅读 1,053评论 1 7