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,211評論 30 472
  • 原文: iOS應用架構談 view層的組織和調用方案 iOS應用架構談 開篇 iOS應用架構談 網絡層設計方案 i...
    難卻卻閱讀 1,278評論 0 7
  • 父類實現深拷貝時,子類如何實現深度拷貝。父類沒有實現深拷貝時,子類如何實現深度拷貝。? 深拷貝同淺拷貝的區別:淺拷...
    JonesCxy閱讀 1,053評論 1 7