NSURLSession實現斷點下載,nsurlsession

來源:互聯網
上載者:User

NSURLSession實現斷點下載,nsurlsession
NSURLSession實現斷點下載

@interfaceHMViewController () <NSURLSessionDownloadDelegate,NSURLSessionDataDelegate]]>

@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

@implementationHMViewController

- (NSURLSession*)session
{
    if (!_session) {
        // 獲得session
        NSURLSessionConfiguration *cfg = [NSURLSessionConfigurationdefaultSessionConfiguration];
        self.session= [NSURLSessionsessionWithConfiguration:cfgdelegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
    }
    return _session;
}

- (IBAction)download:(UIButton*)sender {
    // 按鈕狀態取反
    sender.selected= !sender.isSelected;
   
    if (self.task== nil) { // 開始(繼續)下載
        if (self.resumeData) { // 恢複
            [selfresume];
        } else { // 開始
            [selfstart];
        }
    } else { // 暫停
        [selfpause];
    }
}

/**
 *  從零開始
 */
- (void)start
{
    // 1.建立一個下載任務
    NSURL *url = [NSURLURLWithString:@"http://192.168.15.172:8080/MJServer/resources/videos/minion_01.mp4"];
    self.task= [self.sessiondownloadTaskWithURL:url];
   
    // 2.開始任務
    [self.taskresume];
}

/**
 *  恢複(繼續)
 */
- (void)resume
{
    // 傳入上次暫停下載返回的資料,就可以恢複下載
    self.task= [self.sessiondownloadTaskWithResumeData:self.resumeData];
   
    // 開始任務
    [self.taskresume];
   
    // 清空
    self.resumeData= nil;
}

/**
 *  暫停
 */
- (void)pause
{
    __weak typeof(self) vc =self;
    [self.taskcancelByProducingResumeData:^(NSData*resumeData) {
        //  resumeData : 包含了繼續下載的開始位置\下載的url
        vc.resumeData= resumeData;
        vc.task= nil;
    }];
}

#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession*)session downloadTask:(NSURLSessionDownloadTask*)downloadTask
didFinishDownloadingToURL:(NSURL*)location
{
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) lastObject];
    // response.suggestedFilename : 建議使用的檔案名稱,一般跟伺服器端的檔案名稱一致
    NSString *file = [cachesstringByAppendingPathComponent:downloadTask.response.suggestedFilename];
   
    // 將臨時檔案剪下或者複製Caches檔案夾
    NSFileManager *mgr = [NSFileManagerdefaultManager];
   
    // AtPath : 剪下前的檔案路徑
    // ToPath : 剪下後的檔案路徑
    [mgr moveItemAtPath:location.pathtoPath:fileerror:nil];
}

- (void)URLSession:(NSURLSession*)session downloadTask:(NSURLSessionDownloadTask*)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    NSLog(@"獲得下載進度--%@", [NSThread currentThread]);
    // 獲得下載進度
    self.progressView.progress= (double)totalBytesWritten / totalBytesExpectedToWrite;
}

- (void)URLSession:(NSURLSession*)session downloadTask:(NSURLSessionDownloadTask*)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(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.