iOS開發 - NSURLSession實現斷點續傳下載

來源:互聯網
上載者:User

iOS開發 - NSURLSession實現斷點續傳下載
NSURLSession

1.使用步驟

1> 獲得NSURLSession對象2> 利用NSURLSession對象建立對應的任務(Task)3> 開始任務([task resume])

2.獲得NSURLSession對象

1> [NSURLSession sharedSession]2> NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];

3.任務類型
1> NSURLSessionDataTask
* 用途:用於非檔案下載的GET\POST請求

NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request];NSURLSessionDataTask *task = [self.session dataTaskWithURL:url];NSURLSessionDataTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {}];

2> NSURLSessionDownloadTask
* 用途:用於檔案下載(小檔案、大檔案)

NSURLSessionDownloadTask *task = [self.session downloadTaskWithRequest:request];NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:url];NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {}];
斷點續傳下載執行個體
#import "ViewController.h"@interface ViewController () @property (weak, nonatomic) IBOutlet UIProgressView *progressView;- (IBAction)download:(UIButton *)sender;@property (nonatomic, strong) NSURLSessionDownloadTask *task;@property (nonatomic, strong) NSData *resumeData;@property (nonatomic, strong) NSURLSession *session;@end@implementation ViewController//懶載入- (NSURLSession *)session{    if (!_session) {        // 獲得session        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];        self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];    }    return _session;}- (IBAction)download:(UIButton *)sender {    // 按鈕狀態取反    sender.selected = !sender.isSelected;    if (self.task == nil) { // 開始(繼續)下載        if (self.resumeData) { // 恢複            [self resume];        } else { // 開始            [self start];        }    } else { // 暫停        [self pause];    }}/** *  從零開始 */- (void)start{    // 1.建立一個下載任務    NSURL *url = [NSURL URLWithString:@"http://192.168.1.110:8080/Server/resources"];    self.task = [self.session downloadTaskWithURL:url];    // 2.開始任務    [self.task resume];}/** *  恢複(繼續) */- (void)resume{    // 傳入上次暫停下載返回的資料,就可以恢複下載    self.task = [self.session downloadTaskWithResumeData:self.resumeData];    // 開始任務    [self.task resume];    // 清空    self.resumeData = nil;}/** *  暫停 */- (void)pause{    __weak typeof(self) vc = self;    [self.task cancelByProducingResumeData:^(NSData *resumeData) {        //  resumeData : 包含了繼續下載的開始位置\下載的url        vc.resumeData = resumeData;        vc.task = nil;    }];}#pragma mark - NSURLSessionDownloadDelegate- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTaskdidFinishDownloadingToURL:(NSURL *)location{    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];    // response.suggestedFilename : 建議使用的檔案名稱,一般跟伺服器端的檔案名稱一致    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];    // 將臨時檔案剪下或者複製Caches檔案夾    NSFileManager *mgr = [NSFileManager defaultManager];    // AtPath : 剪下前的檔案路徑    // ToPath : 剪下後的檔案路徑    [mgr moveItemAtPath:location.path toPath:file error:nil];}- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask      didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWrittentotalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{    NSLog(@"獲得下載進度--%@", [NSThread currentThread]);    // 獲得下載進度    self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite;}- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffsetexpectedTotalBytes:(int64_t)expectedTotalBytes{}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.