1. 程式人生 > >網路:NSURLSession 下載暫停與繼續

網路:NSURLSession 下載暫停與繼續

#import "ViewController.h"
#import "SSZipArchive.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (nonatomic, strong) NSURLSession *session; // 自定義會話
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask; // 下載任務
@end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"%@",NSHomeDirectory()); // Do any additional setup after loading the view, typically from a nib. } // 在暫停或者繼續之前先判斷當前的任務狀態 - (IBAction)pause:(id)sender { // 只有在執行狀態的才能暫停 if (self.downloadTask.state
== NSURLSessionTaskStateRunning) { NSLog(@"暫停"); [self.downloadTask suspend]; } } - (IBAction)resume:(id)sender { if (self.downloadTask.state == NSURLSessionTaskStateSuspended) { NSLog(@"繼續"); [self.downloadTask resume]; } } // 使用NSURLSession 下載,記憶體鋒值不高。但是有些Xcode版本,峰值很6.3以前
// 但是在真機上不存在這個問題 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { // NSURL NSURL *url = [NSURL URLWithString:@"http://dlsw.baidu.com/sw-search-sp/soft/c6/25790/WeChatzhCN1.0.0.6.1428545414.dmg"]; // NSURL *url = [NSURL URLWithString:@"http://localhost/09.zip"]; // Session發起請求 // location 檔案下載完這後儲存的路徑 // 單例可以在多個控制器使用 // [[self.session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { // NSLog(@"%@ -- %@",location.path, response); // // 下載完檔案之後,檔案被刪除了 // // 因為系統以為你下載的是壓縮包,下載完成之後需要解壓。解壓完成之後,刪除原檔案 // // 解壓 // /* // 1. 壓縮包的路徑 // 2. 解壓到的路徑 // */ //// [SSZipArchive unzipFileAtPath:location.path toDestination:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]]; // // // 下載視訊,需要解壓嗎 不需要 // // 複製一份到另一個目錄 // NSFileManager *manager = [NSFileManager defaultManager]; // // 儲存檔案的路徑 // NSString *fileName = [url.path lastPathComponent]; // NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:fileName]; // // // 把臨時檔案移動到快取目錄,並且改成我們需要的字尾名 // // 使用複製或者移動都可以 //// [manager moveItemAtPath:location.path toPath:path error:NULL]; // [manager copyItemAtPath:location.path toPath:path error:NULL]; // }] resume]; // 防止點選多次 // 下載任務 self.downloadTask = [self.session downloadTaskWithURL:url]; // 繼續(開始)下載 [self.downloadTask resume]; } #pragma mark - Session 的代理 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { // NSLog(@"%@",location); NSLog(@"下載完成,開始移動檔案"); // 處理下載完成的檔案 // NSFileManager *manager = [NSFileManager defaultManager]; // // 儲存檔案的路徑 // NSString *fileName = @"123.mp4"; // NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:fileName]; // // // 把臨時檔案移動到快取目錄,並且改成我們需要的字尾名 // // 使用複製或者移動都可以 // // [manager moveItemAtPath:location.path toPath:path error:NULL]; // [manager copyItemAtPath:location.path toPath:path error:NULL]; } // 此方法並沒什麼卵用 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { NSLog(@"didResumeAtOffset"); } /** session 會話 downloadTask 任務的物件 bytesWritten 本次寫入的資料長度 totalBytesWritten 總共接收了資料長度 totalBytesExpectedToWrite 總的資料長度 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { //得到下載進度 CGFloat progress = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite; NSLog(@"%f - %@",progress,[NSThread currentThread]); //回到主執行緒重新整理UI dispatch_async(dispatch_get_main_queue(), ^{ self.progressView.progress = progress; }); } - (NSURLSession *)session { if (_session == nil) { // 建立配置物件 通常使用預設的配置就可以了 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; /* delegateQueue 如果設定nil , 代理在子執行緒回撥,序列佇列 [[NSOperationQueue alloc]init] 還是在同一時間內只開啟一條執行緒 [NSOperationQueue mainQueue] 在主執行緒回撥 */ _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; } return _session; } @end