iOS -- NSURLSession 實現斷點下載

iOS -- NSURLSession 實現斷點下載html

NSURLSession是iOS7中新的網絡接口,它與我們熟悉的NSURLConnection是並列的。在程序在前臺時,NSURLSession與NSURLConnection能夠互爲替代工做。注意,若是用戶強制將程序關閉,NSURLSession會斷掉。網絡

NSURLSession提供的功能:session

1.經過URL將數據下載到內存atom

2.經過URL將數據下載到文件系統url

3.將數據上傳到指定URLspa

4.在後臺完成上述功能代理


若是想更深刻的瞭解NSURLSession  請點擊 http://www.cocoachina.com/industry/20131106/7304.html code


好啦!步入正題,斷點下載的實現htm











控件已經拖好,而且關聯了點擊事件,下面就是代碼部分了。對象

  1. 在viewController.m 文件中聲明屬性

@property (nonatomic,strong) NSURLSessionDownloadTask *task;


    2.建立一個任務配置對象

    在viewDidLoad 中寫入一下代碼

 NSURLSessionConfiguration *configer = [NSURLSessionConfiguration defaultSessionConfiguration];
    
 NSURLSession *session = [NSURLSession sessionWithConfiguration:configer delegate:self delegateQueue:[NSOperationQueue mainQueue]];
 //這裏設置代理了,因此須要去遵照兩個協議  NSURLSessionDataDelegate,NSURLSessionDelegate
    
    NSURL *url = [NSURL URLWithString:@"http://uploads.mp3songurls.com/2930.mp3"];
    
    //建立下載任務
    self.task = [session downloadTaskWithURL:url];


    3.下載過程當中須要實現代理的方法

#pragma mark 每下載完一部分 就會調用該方法   
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //文件以字節爲單位
    //1.totalBytesExpectedToWrite 所需下載文件的總大小
    //2.totalBytesWritten 已經下載好部分的大小
    //3.bytesWritten 當前(本次)下載文件的大小
    self.progressView.progress = 1.0f * totalBytesWritten/totalBytesExpectedToWrite;
    NSLog(@"%.2f",self.progressView.progress);
    
}


    4.下載完成調用的方法

#pragma mark  下載完成的代理方法  
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{

    //打印一下沙盒地址,去沙盒裏面查看下載好的文件
    NSLog(@"%@",NSHomeDirectory());
    
    //建立下載文件保存的路徑,通常大文件都會保存在cache文件下
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    cachePath = [cachePath stringByAppendingPathComponent:@"111.mp3"];
    NSFileManager *manager = [NSFileManager defaultManager];
    //將下載好的文件移動到cache文件夾下,由於下載的文件,默認是在tmp目錄下,這個目錄最大的特色就是,一段時間以後,系統將對該文件下的文件作一個清理的操做,這是自動執行的
    [manager moveItemAtPath:location.path toPath:cachePath error:nil];
    
}


    5.開始下載的方法

#pragma mark 開始下載
- (IBAction)startDownloadDidClickedAction:(id)sender {
    [self.task resume];
}

    

    6.暫停下載

    

#pragma mark 暫停下載  
- (IBAction)stopButtonDIdClickedAction:(id)sender {
    [self.task suspend];
}



    這只是作了個小小的介紹,但願對有須要的童鞋有幫助。。。。

相關文章
相關標籤/搜索