標籤:
#import "ViewController.h"@interface ViewController ()<NSURLSessionDataDelegate>@property (weak, nonatomic) IBOutlet UIProgressView *proessView;/** 接受響應體資訊 */@property (nonatomic, strong) NSFileHandle *handle;@property (nonatomic, assign) NSInteger totalSize;@property (nonatomic, assign) NSInteger currentSize;@property (nonatomic, strong) NSString *fullPath;@end@implementation ViewController-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ //1.url NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_02.mp4"]; //2.建立請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.建立會話對象,設定代理 /* 第一個參數:配置資訊 [NSURLSessionConfiguration defaultSessionConfiguration] 第二個參數:代理 第三個參數:設定代理方法在哪個線程中調用 */ NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; //4.建立Task NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request]; //5.執行Task [dataTask resume];}#pragma mark ----------------------#pragma mark NSURLSessionDataDelegate/** * 1.接收到伺服器的響應 它預設會取消該請求 * * @param session 會話對象 * @param dataTask 請求任務 * @param response 回應標頭資訊 * @param completionHandler 回調 傳給系統 */-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{ //獲得檔案的總大小 self.totalSize = response.expectedContentLength; //獲得檔案全路徑 self.fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename]; //建立空的檔案 [[NSFileManager defaultManager]createFileAtPath:self.fullPath contents:nil attributes:nil]; //建立檔案控制代碼 self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullPath]; [self.handle seekToEndOfFile]; /* NSURLSessionResponseCancel = 0,取消 預設 NSURLSessionResponseAllow = 1, 接收 NSURLSessionResponseBecomeDownload = 2, 變成下載任務 NSURLSessionResponseBecomeStream 變成流 */ completionHandler(NSURLSessionResponseAllow);}/** * 接收到伺服器返回的資料 調用多次 * * @param session 會話對象 * @param dataTask 請求任務 * @param data 本次下載的資料 */-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{ //寫入資料到檔案 [self.handle writeData:data]; //計算檔案的下載進度 self.currentSize += data.length; NSLog(@"%f",1.0 * self.currentSize / self.totalSize); self.proessView.progress = 1.0 * self.currentSize / self.totalSize;}/** * 請求結束或者是失敗的時候調用 * * @param session 會話對象 * @param dataTask 請求任務 * @param error 錯誤資訊 */-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ NSLog(@"%@",self.fullPath); //關閉檔案控制代碼 [self.handle closeFile]; self.handle = nil;}@end
ios開發網路學習十:利用檔案控制代碼實現大檔案下載