#import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
//顯示進度label
@property (weak, nonatomic) IBOutlet UILabel *progressPercentLabel;
//進度視圖
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
//下載任務
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;
//session會話
@property (nonatomic, strong) NSURLSession *session;
//記錄點擊暫停按鈕時返回的數據點(附加信息)
@property (nonatomic, strong) NSData *resumeData;
@end
@implementation ViewController
- (IBAction)startDownloadImage:(id)sender {
//0.NSURL
NSURL *url = [NSURL URLWithString:@"http://images.apple.com/v/iphone-5s/gallery/a/images/download/photo_4.jpg"];
//1.session
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//2.task
self.downloadTask = [self.session downloadTaskWithURL:url];
//3.resume(執行)
[self.downloadTask resume];
}
//暫停正在下載的任務
- (IBAction)cancelImage:(id)sender {
[self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
//resumeData:在點擊暫停按鈕的時候的已經下載的數據(Range)
if (!resumeData) {
return;
}
self.resumeData = resumeData;
}];
}
//恢復下載任務(重新發送請求)
- (IBAction)resumeImage:(id)sender {
if (self.resumeData) {
self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
//重新執行下載任務
[self.downloadTask resume];
}
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
//更新進度視圖值
self.progressView.progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
//更新label文本(目前下載總大小/總大小)
self.progressPercentLabel.text = [NSString stringWithFormat:@"%lld/%lld",totalBytesWritten, totalBytesExpectedToWrite];
}
//必須實現的方法!!!
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
}
NSURLSessionDownloadTask下載圖片
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
推薦閱讀更多精彩內容
- Python應用現在如火如荼,應用范圍很廣。因其效率高開發迅速的優勢,快速進入編程語言排行榜前幾名。本系列文章致力...
- 為按鈕設置網絡圖片, 可以使用SDWebImage第三方庫提供的UIButton+WebCache.h 分類 提供...
- 簡粉下載是一款可以將簡書上的文章保存為HTML和PDF文件的Windows軟件,圖文排版與簡書保持一致,為文章(包...
- 一談起中國電競,大家最先想到的是什么? WCG?外國的。 魔獸,外國的。 星際,外國的。 CF,外國的。 DNF,...