一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - IOS - iOS開發-實現大文件下載與斷點下載思路

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

2021-03-01 16:56Jierism IOS

本篇文章主要介紹了iOS開發-實現大文件下載與斷點下載思路,具有一定的參考價值,感興趣的小伙伴們可以參考一下。

大文件下載

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

相關變量:

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

1>發送請求

?
1
2
3
4
5
// 創建一個請求
  NSURL *url = [NSURL URLWithString:@""];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  // 使用NSURLConnection發起一個異步請求
  [NSURLConnection connectionWithRequest:request delegate:self];

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/** 在接收到服務器的響應時調用下面這個代理方法
  1.創建一個空文件
  2.用一個句柄對象關聯這個空文件,目的是方便在空文件后面寫入數據
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
  // 創建文件路徑
  NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
  NSString *filePath = [caches stringByAppendingPathComponent:@"videos.zip"];
  
  // 創建一個空的文件到沙盒中
  NSFileManager *mgr = [NSFileManager defaultManager];
  [mgr createFileAtPath:filePath contents:nil attributes:nil];
  
  // 創建一個用來寫數據的文件句柄
  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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 :臨時文件存放的路徑(下載好的文件)
    
    // 創建存儲文件路徑
    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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
  // 創建一個下載任務并設置代理
  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{
  // 創建存儲文件路徑
  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
{
  // 用于斷點續傳
}

斷點下載

方案一:

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

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

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- (IBAction)download:(UIButton *)sender {
  
  sender.selected = !sender.isSelected;
  
  if (sender.selected) { // 繼續(開始)下載
    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>在接受到服務器響應執行的代理方法中第一行添加下面代碼,防止重復創建空文件

?
1
if (self.currentLength) return;

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

所需變量

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

方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// 懶加載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) { // 開始(繼續)下載
    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 : 包含了繼續下載的開始位置和下載的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{
  // 創建存儲文件路徑
  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
{
}

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

原文鏈接:http://www.cnblogs.com/jierism/p/6284304.html

延伸 · 閱讀

精彩推薦
  • IOSiOS中MD5加密算法的介紹和使用

    iOS中MD5加密算法的介紹和使用

    MD5加密是最常用的加密方法之一,是從一段字符串中通過相應特征生成一段32位的數字字母混合碼。對輸入信息生成唯一的128位散列值(32個字符)。這篇文...

    LYSNote5432021-02-04
  • IOSiOS中滑動控制屏幕亮度和系統音量(附加AVAudioPlayer基本用法和Masonry簡單使用)

    iOS中滑動控制屏幕亮度和系統音量(附加AVAudioPlayer基本用法和

    這篇文章主要介紹了iOS中滑動控制屏幕亮度和系統音量(附加AVAudioPlayer基本用法和Masonry簡單使用)的相關資料,需要的朋友可以參考下...

    CodingFire13652021-02-26
  • IOSiOS實現控制屏幕常亮不變暗的方法示例

    iOS實現控制屏幕常亮不變暗的方法示例

    最近在工作中遇到了要將iOS屏幕保持常亮的需求,所以下面這篇文章主要給大家介紹了關于利用iOS如何實現控制屏幕常亮不變暗的方法,文中給出了詳細的...

    隨風13332021-04-02
  • IOSiOS自定義UICollectionViewFlowLayout實現圖片瀏覽效果

    iOS自定義UICollectionViewFlowLayout實現圖片瀏覽效果

    這篇文章主要介紹了iOS自定義UICollectionViewFlowLayout實現圖片瀏覽效果的相關資料,需要的朋友可以參考下...

    jiangamh8882021-01-11
  • IOSiOS中UILabel實現長按復制功能實例代碼

    iOS中UILabel實現長按復制功能實例代碼

    在iOS開發過程中,有時候會用到UILabel展示的內容,那么就設計到點擊UILabel復制它上面展示的內容的功能,也就是Label長按復制功能,下面這篇文章主要給大...

    devilx12792021-04-02
  • IOSiOS開發之視圖切換

    iOS開發之視圖切換

    在iOS開發中視圖的切換是很頻繁的,獨立的視圖應用在實際開發過程中并不常見,除非你的應用足夠簡單。在iOS開發中常用的視圖切換有三種,今天我們將...

    執著丶執念5282021-01-16
  • IOS詳解iOS中多個網絡請求的同步問題總結

    詳解iOS中多個網絡請求的同步問題總結

    這篇文章主要介紹了詳解iOS中多個網絡請求的同步問題總結,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧...

    liang199111312021-03-15
  • IOSiOS開發技巧之狀態欄字體顏色的設置方法

    iOS開發技巧之狀態欄字體顏色的設置方法

    有時候我們需要根據不同的背景修改狀態欄字體的顏色,下面這篇文章主要給大家介紹了關于iOS開發技巧之狀態欄字體顏色的設置方法,文中通過示例代碼...

    夢想家-mxj8922021-05-10
主站蜘蛛池模板: 色伦网 | 天美传媒tm0065 | 四虎精品免费国产成人 | 男人午夜视频在线观看 | 日本videos有奶水的hd | 午夜影院0606 | 日本高清色视影www日本 | 国产乱码免费卡1卡二卡3卡四 | 青青国产在线视频 | 欧美日韩在线一区 | 女高h | 国产91精选在线观看麻豆 | 99精品国产自在现线观看 | 第一福利在线观看永久视频 | 色综合图区| 色涩导航 | 免费视频左左视频 | 日本人添下面的全过程 | 幻女free性俄罗斯第一次摘花 | 性吟网| 99网站在线观看 | 无毛黄片 | 人配人种视频xxxx | 1024国产看片在线观看 | 电车痴汉(han) | 天美传媒在线视频 | 日本久本草精品 | 亚洲丰满模特裸做爰 | 亚洲视频第一页 | 97色伦在线观看 | 亚洲区精品久久一区二区三区 | 国产在线综合网 | 欧美同志gaypronvideos | 美女狂揉尿口揉到失禁 | 99这里只有精品视频 | 午夜小视频免费 | 午夜亚洲精品久久久久久 | 四虎国产精品免费久久麻豆 | 国产这里有精品 | 好湿好滑好硬好爽好深视频 | 天堂在线中文无弹窗全文阅读 |