最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

iOS開發(fā)-實現大文件下載與斷點下載思路

 更新時間:2017年01月14日 14:20:48   作者:Jierism  
本篇文章主要介紹了iOS開發(fā)-實現大文件下載與斷點下載思路,具有一定的參考價值,感興趣的小伙伴們可以參考一下。

大文件下載

方案一:利用NSURLConnection和它的代理方法,及NSFileHandle(iOS9后不建議使用)

相關變量:

 @property (nonatomic,strong) NSFileHandle *writeHandle;
@property (nonatomic,assign) long long totalLength; 

1>發(fā)送請求

// 創(chuàng)建一個請求
  NSURL *url = [NSURL URLWithString:@""];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  // 使用NSURLConnection發(fā)起一個異步請求
  [NSURLConnection connectionWithRequest:request delegate:self]; 

2>在代理方法中處理服務器返回的數據

/** 在接收到服務器的響應時調用下面這個代理方法
  1.創(chuàng)建一個空文件
  2.用一個句柄對象關聯這個空文件,目的是方便在空文件后面寫入數據
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
  // 創(chuàng)建文件路徑
  NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
  NSString *filePath = [caches stringByAppendingPathComponent:@"videos.zip"];
  
  // 創(chuàng)建一個空的文件到沙盒中
  NSFileManager *mgr = [NSFileManager defaultManager];
  [mgr createFileAtPath:filePath contents:nil attributes:nil];
  
  // 創(chuàng)建一個用來寫數據的文件句柄
  self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  
  // 獲得文件的總大小
  self.totalLength = response.expectedContentLength;
}

/** 在接收到服務器返回的文件數據時調用下面這個代理方法
  利用句柄對象往文件的最后面追加數據
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
{
  // 移動到文件的最后面
  [self.writeHandle seekToEndOfFile];
  
  // 將數據寫入沙盒
  [self.writeHandle writeData:data];
}

/**
  在所有數據接收完畢時,關閉句柄對象
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  // 關閉文件并清空
  [self.writeHandle closeFile];
  self.writeHandle = nil;
} 

方案二:使用NSURLSession的NSURLSessionDownloadTask和NSFileManager

NSURLSession *session = [NSURLSession sharedSession];
  NSURL *url = [NSURL URLWithString:@""];
  // 可以用來下載大文件,數據將會存在沙盒里的tmp文件夾
  NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    // location :臨時文件存放的路徑(下載好的文件)
    
    // 創(chuàng)建存儲文件路徑
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    // response.suggestedFilename:建議使用的文件名,一般跟服務器端的文件名一致
    NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
    
    /**將臨時文件剪切或者復制到Caches文件夾
     AtPath :剪切前的文件路徑
     toPath :剪切后的文件路徑
     */
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr moveItemAtPath:location.path toPath:file error:nil];
  }];
  [task resume]; 

方案三:使用NSURLSessionDownloadDelegate的代理方法和NSFileManger

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
  // 創(chuàng)建一個下載任務并設置代理
  NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
  NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  
  NSURL *url = [NSURL URLWithString:@""];
  NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
  [task resume];
}

#pragma mark - 
/**
  下載完畢后調用
  參數:lication 臨時文件的路徑(下載好的文件)
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
  // 創(chuàng)建存儲文件路徑
  NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
  // response.suggestedFilename:建議使用的文件名,一般跟服務器端的文件名一致
  NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
  
  /**將臨時文件剪切或者復制到Caches文件夾
   AtPath :剪切前的文件路徑
   toPath :剪切后的文件路徑
   */
  NSFileManager *mgr = [NSFileManager defaultManager];
  [mgr moveItemAtPath:location.path toPath:file error:nil];
}

/**
  每當下載完一部分時就會調用(可能會被調用多次)
  參數:
    bytesWritten 這次調用下載了多少
    totalBytesWritten 累計寫了多少長度到沙盒中了
    totalBytesExpectedToWrite 文件總大小
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
   didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
  // 這里可以做些顯示進度等操作
}

/**
  恢復下載時使用
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
  // 用于斷點續(xù)傳
} 

斷點下載

方案一:

1>在方案一的基礎上新增兩個變量和按扭

@property (nonatomic,assign) long long currentLength;
@property (nonatomic,strong) NSURLConnection *conn; 

2>在接收到服務器返回數據的代理方法中添加如下代碼

  // 記錄斷點,累計文件長度
  self.currentLength += data.length; 

3>點擊按鈕開始(繼續(xù))或暫停下載

- (IBAction)download:(UIButton *)sender {
  
  sender.selected = !sender.isSelected;
  
  if (sender.selected) { // 繼續(xù)(開始)下載
    NSURL *url = [NSURL URLWithString:@""];
    // ****關鍵點是使用NSMutableURLRequest,設置請求頭Range
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
    
    NSString *range = [NSString stringWithFormat:@"bytes=%lld-",self.currentLength];
    [mRequest setValue:range forHTTPHeaderField:@"Range"];
    
    // 下載
    self.conn = [NSURLConnection connectionWithRequest:mRequest delegate:self];
  }else{
    [self.conn cancel];
    self.conn = nil;
  }
} 

4>在接受到服務器響應執(zhí)行的代理方法中第一行添加下面代碼,防止重復創(chuàng)建空文件

 if (self.currentLength) return; 

方案二:使用NSURLSessionDownloadDelegate的代理方法

所需變量

 @property (nonatomic,strong) NSURLSession *session;
@property (nonatomic,strong) NSData *resumeData; //包含了繼續(xù)下載的開始位置和下載的url
@property (nonatomic,strong) NSURLSessionDownloadTask *task; 

方法

// 懶加載session
- (NSURLSession *)session
{
  if (!_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) { // 開始(繼續(xù))下載
    if (self.resumeData) { // 原先有數據則恢復
      [self resume];
    }else{
      [self start]; // 原先沒有數據則開始
    }
  }else{ // 暫停
    [self pause];
  }
}

// 從零開始
- (void)start{
  NSURL *url = [NSURL URLWithString:@""];
  self.task = [self.session downloadTaskWithURL:url];
  [self.task resume];
}

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

// 恢復
- (void)resume{
  // 傳入上次暫停下載返回的數據,就可以回復下載
  self.task = [self.session downloadTaskWithResumeData:self.resumeData];
  // 開始任務
  [self.task resume];
  // 清空
  self.resumeData = nil;
}

#pragma mark - NSURLSessionDownloadDelegate
/**
  下載完畢后調用
  參數:lication 臨時文件的路徑(下載好的文件)
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
  // 創(chuàng)建存儲文件路徑
  NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
  // response.suggestedFilename:建議使用的文件名,一般跟服務器端的文件名一致
  NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
  
  /**將臨時文件剪切或者復制到Caches文件夾
   AtPath :剪切前的文件路徑
   toPath :剪切后的文件路徑
   */
  NSFileManager *mgr = [NSFileManager defaultManager];
  [mgr moveItemAtPath:location.path toPath:file error:nil];
}

/**
  每當下載完一部分時就會調用(可能會被調用多次)
  參數:
    bytesWritten 這次調用下載了多少
    totalBytesWritten 累計寫了多少長度到沙盒中了
    totalBytesExpectedToWrite 文件總大小
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
   didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
  // 這里可以做些顯示進度等操作
}

/**
  恢復下載時使用
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • 詳解IOS的Automatically Sign在設備上打包

    詳解IOS的Automatically Sign在設備上打包

    本篇教程主要給大家分享了IOS的Automatically Sign如何在設備上直接打包,有需要的朋友參考學習下。
    2018-01-01
  • iOS 雷達效果實例詳解

    iOS 雷達效果實例詳解

    這篇文章主要介紹了iOS 雷達效果實例詳解的相關資料,需要的朋友可以參考下
    2016-09-09
  • 詳解iOS學習筆記(十七)——文件操作(NSFileManager)

    詳解iOS學習筆記(十七)——文件操作(NSFileManager)

    這篇文章主要介紹了詳解iOS學習筆記(十七)——文件操作(NSFileManager),具有一定的參考價值,有需要的可以了解一下。
    2016-12-12
  • iOS微信瀏覽器回退不刷新實例(監(jiān)聽瀏覽器回退事件)

    iOS微信瀏覽器回退不刷新實例(監(jiān)聽瀏覽器回退事件)

    下面小編就為大家?guī)硪黄猧OS微信瀏覽器回退不刷新實例(監(jiān)聽瀏覽器回退事件)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05
  • NSString屬性何時用strong何時用copy?

    NSString屬性何時用strong何時用copy?

    相信各位iOS開發(fā)者們都考慮過這個問題,平時寫NSString的屬性時都用copy,那strong要何時用呢?下面這篇文章就來看一下什么時候應該用copy,什么時候應該用strong。有需要的朋友們可以參考借鑒,下面來一起看看吧。
    2016-12-12
  • IOS開發(fā)之路--C語言基礎知識

    IOS開發(fā)之路--C語言基礎知識

    當前移動開發(fā)的趨勢已經勢不可擋,這個系列希望淺談一下個人對IOS開發(fā)的一些見解,今天我們從最基礎的C語言開始,C語言部分我將分成幾個章節(jié)去說,今天我們簡單看一下C的一些基礎知識,更高級的內容我將放到后面的文章中。
    2014-08-08
  • iOS超出父控件范圍無法點擊問題解決

    iOS超出父控件范圍無法點擊問題解決

    這篇文章主要介紹了iOS超出父控件范圍無法點擊問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-06-06
  • IOS第三方庫ZXEasyCoding

    IOS第三方庫ZXEasyCoding

    本文給大家簡單介紹了object-c的第三方庫ZXEasyCoding的安裝、示例以及github地址,有需要的小伙伴可以參考下
    2016-11-11
  • 詳解 iOS 系統中的視圖動畫

    詳解 iOS 系統中的視圖動畫

    這篇文章主要介紹了iOS 系統中的視圖動畫的的相關資料,幫助大家更好的理解和學習使用ios開發(fā),感興趣的朋友可以了解下
    2021-02-02
  • iOS Runtime詳解(新手也看得懂)

    iOS Runtime詳解(新手也看得懂)

    這篇文章主要給大家介紹了關于iOS Runtime的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-02-02

最新評論

璧山县| 塔城市| 竹山县| 中西区| 武川县| 盘山县| 陈巴尔虎旗| 章丘市| 双鸭山市| 西盟| 合山市| 牙克石市| 新巴尔虎右旗| 宜兰县| 牡丹江市| 三门县| 合阳县| 池州市| 巨野县| 务川| 雷山县| 高雄市| 通许县| 孟州市| 金平| 隆昌县| 永州市| 桑植县| 遵义市| 贵港市| 搜索| 新密市| 河曲县| 普定县| 瓦房店市| 宝清县| 灵宝市| 隆子县| 天全县| 商洛市| 娱乐|