NSURLSessionDownloadTask 加MBProgressHUD的簡單應(yīng)用

新建工具類繼承于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) {
        //創(chuàng)建一個(gè)下載任務(wù)
        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) {
        //設(shè)置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;
    //拼接文件的名字,名字是服務(wù)器給的
    NSString *filename = downloadTask.response.suggestedFilename;
    
    filepath = [filepath stringByAppendingPathComponent:filename];
    //文件管理器,將臨時(shí)文件移動(dòng)到緩存文件中
    [[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>
//設(shè)置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];

點(diǎn)擊事件
#開始
- (IBAction)startDownloadAction:(UIButton *)sender {
    //開始下載
    [self.mydownload startDownload];
    
    //設(shè)置任務(wù)進(jìn)行時(shí)需要做的事情
    self.hub.labelText = @"請稍等";
    
    //設(shè)置提示框樣,MBProgressHUDModeDeterminate是個(gè)枚舉值
    self.hub.mode = MBProgressHUDModeDeterminate;
    
    //設(shè)置任務(wù)進(jìn)行時(shí)的動(dòng)畫
    [self.hub showAnimated:YES whileExecutingBlock:^{

        while (self.progresss < 1.0f) {

            self.hub.progress = self.progresss;
            usleep(50000);
        }
        
    }completionBlock:^{
        //任務(wù)完成之后需要做的事情
        
        [self.hub removeFromSuperViewOnHide];
        self.hub = nil;
        self.hub.labelText = @"下載成功";
        //文本提示框
        self.hub.mode = MBProgressHUDModeCustomView;
        
        [self.hub showAnimated:YES whileExecutingBlock:^{
            //設(shè)置文本提示框消失的時(shí)間(單位為秒)
            sleep(2);
        } completionBlock:^{
            //當(dāng)文本框消失后把它移除
            [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

運(yùn)行

123.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 2,055評論 0 9
  • 1,NSObject中description屬性的意義,它可以重寫嗎?答案:每當(dāng) NSLog(@"")函數(shù)中出現(xiàn) ...
    eightzg閱讀 4,340評論 2 19
  • *面試心聲:其實(shí)這些題本人都沒怎么背,但是在上海 兩周半 面了大約10家 收到差不多3個(gè)offer,總結(jié)起來就是把...
    Dove_iOS閱讀 27,619評論 30 472
  • 原文: iOS應(yīng)用架構(gòu)談 view層的組織和調(diào)用方案 iOS應(yīng)用架構(gòu)談 開篇 iOS應(yīng)用架構(gòu)談 網(wǎng)絡(luò)層設(shè)計(jì)方案 i...
    難卻卻閱讀 1,384評論 0 7
  • 父類實(shí)現(xiàn)深拷貝時(shí),子類如何實(shí)現(xiàn)深度拷貝。父類沒有實(shí)現(xiàn)深拷貝時(shí),子類如何實(shí)現(xiàn)深度拷貝。? 深拷貝同淺拷貝的區(qū)別:淺拷...
    JonesCxy閱讀 1,203評論 1 7

友情鏈接更多精彩內(nèi)容