NSURLSessionDownloadTask下載圖片

#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 {
    
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容