本文首發於我的個人博客:『不羈閣』 https://bujige.net
文章鏈接:https://bujige.net/blog/iOS-Resume-Download-AFNetworking.html
目錄
- AFNetworking下載簡介
- AFNetworking下載相關
2.1 AFNetworking(文件下載)
2.2 AFNetworking(斷點下載 | 支持離線)
關於『文件下載、斷點下載』所有實現的Demo地址:Demo地址
iOS網絡--『文件下載、斷點下載』的實現相關文章:
- iOS網絡--『文件下載、斷點下載』的實現(一):NSURLConnection
- iOS網絡--『文件下載、斷點下載』的實現(二):NSURLSession
- iOS網絡--『文件下載、斷點下載』的實現(三):AFNetworking
1. AFNetworking下載簡介
這裏只講解AFNetworking下載文件相關知識。對於第三方框架的導入在這裏不做講解,如果有問題可以上AFNetworking的GitHub上了解。—> AFNetworking官方地址
2. AFNetworking下載相關
2.1 AFNetworking(文件下載)
AFNetworking實現文件下載總共四步:
- 創建會話管理者
- 創建下載路徑和請求對象
- 創建下載任務
- 啓動下載任務
具體實現代碼如下:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// 1. 創建會話管理者
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
// 2. 創建下載路徑和請求對象
NSURL *URL = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
// 3.創建下載任務
/**
* 第一個參數 - request:請求對象
* 第二個參數 - progress:下載進度block
* 其中: downloadProgress.completedUnitCount:已經完成的大小
* downloadProgress.totalUnitCount:文件的總大小
* 第三個參數 - destination:自動完成文件剪切操作
* 其中: 返回值:該文件應該被剪切到哪裏
* targetPath:臨時路徑 tmp NSURL
* response:響應頭
* 第四個參數 - completionHandler:下載完成回調
* 其中: filePath:真實路徑 == 第三個參數的返回值
* error:錯誤信息
*/
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) {
// 下載進度
self.progressView.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
self.progressLabel.text = [NSString stringWithFormat:@"當前下載進度:%.2f%%",100.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount];
} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *path = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [path URLByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
// 4. 開啓下載任務
[downloadTask resume];
2.2 AFNetworking(斷點下載 | 支持離線)
- AFNetworking3.0是基於NSURLSession的。所以實現原理和NSURLSession差不多。可參考NSURLConnection實現斷點下載的方法。
這裏使用了NSURLSessionDataTask,以便實現『離線斷點下載』。
具體實現步驟如下:
- 定義下載文件需要用到的類,這裏不需要實現代理
@interface ViewController ()
/** 下載進度條 */
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** 下載進度條Label */
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;
/** AFNetworking斷點下載(支持離線)需用到的屬性 **********/
/** 文件的總長度 */
@property (nonatomic, assign) NSInteger fileLength;
/** 當前下載長度 */
@property (nonatomic, assign) NSInteger currentLength;
/** 文件句柄對象 */
@property (nonatomic, strong) NSFileHandle *fileHandle;
/** 下載任務 */
@property (nonatomic, strong) NSURLSessionDataTask *downloadTask;
/* AFURLSessionManager */
@property (nonatomic, strong) AFURLSessionManager *manager;
@end
- 添加全局NSURLSessionDataTask、AFURLSessionManager懶加載代碼。這裏我把實現『離線斷點下載』的代碼都放這裏了。
/**
* manager的懶加載
*/
- (AFURLSessionManager *)manager {
if (!_manager) {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// 1. 創建會話管理者
_manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
}
return _manager;
}
/**
* downloadTask的懶加載
*/
- (NSURLSessionDataTask *)downloadTask {
if (!_downloadTask) {
// 創建下載URL
NSURL *url = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
// 2.創建request請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 設置HTTP請求頭中的Range
NSString *range = [NSString stringWithFormat:@"bytes=%zd-", self.currentLength];
[request setValue:range forHTTPHeaderField:@"Range"];
__weak typeof(self) weakSelf = self;
_downloadTask = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSLog(@"dataTaskWithRequest");
// 清空長度
weakSelf.currentLength = 0;
weakSelf.fileLength = 0;
// 關閉fileHandle
[weakSelf.fileHandle closeFile];
weakSelf.fileHandle = nil;
}];
[self.manager setDataTaskDidReceiveResponseBlock:^NSURLSessionResponseDisposition(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSURLResponse * _Nonnull response) {
NSLog(@"NSURLSessionResponseDisposition");
// 獲得下載文件的總長度:請求下載的文件長度 + 當前已經下載的文件長度
weakSelf.fileLength = response.expectedContentLength + self.currentLength;
// 沙盒文件路徑
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
NSLog(@"File downloaded to: %@",path);
// 創建一個空的文件到沙盒中
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:path]) {
// 如果沒有下載文件的話,就創建一個文件。如果有下載文件的話,則不用重新創建(不然會覆蓋掉之前的文件)
[manager createFileAtPath:path contents:nil attributes:nil];
}
// 創建文件句柄
weakSelf.fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
// 允許處理服務器的響應,纔會繼續接收服務器返回的數據
return NSURLSessionResponseAllow;
}];
[self.manager setDataTaskDidReceiveDataBlock:^(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSData * _Nonnull data) {
NSLog(@"setDataTaskDidReceiveDataBlock");
// 指定數據的寫入位置 -- 文件內容的最後面
[weakSelf.fileHandle seekToEndOfFile];
// 向沙盒寫入數據
[weakSelf.fileHandle writeData:data];
// 拼接文件總長度
weakSelf.currentLength += data.length;
// 獲取主線程,不然無法正確顯示進度。
NSOperationQueue* mainQueue = [NSOperationQueue mainQueue];
[mainQueue addOperationWithBlock:^{
// 下載進度
if (weakSelf.fileLength == 0) {
weakSelf.progressView.progress = 0.0;
weakSelf.progressLabel.text = [NSString stringWithFormat:@"當前下載進度:00.00%%"];
} else {
weakSelf.progressView.progress = 1.0 * weakSelf.currentLength / weakSelf.fileLength;
weakSelf.progressLabel.text = [NSString stringWithFormat:@"當前下載進度:%.2f%%",100.0 * weakSelf.currentLength / weakSelf.fileLength];
}
}];
}];
}
return _downloadTask;
}
- 添加支持斷點下載的[開始下載/暫停下載]按鈕,並實現相應功能的代碼
/**
* 點擊按鈕 -- 使用AFNetworking斷點下載(支持離線)
*/
- (IBAction)OfflinResumeDownloadBtnClicked:(UIButton *)sender {
// 按鈕狀態取反
sender.selected = !sender.isSelected;
if (sender.selected) { // [開始下載/繼續下載]
// 沙盒文件路徑
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
NSInteger currentLength = [self fileLengthForPath:path];
if (currentLength > 0) { // [繼續下載]
self.currentLength = currentLength;
}
[self.downloadTask resume];
} else {
[self.downloadTask suspend];
self.downloadTask = nil;
}
}
/**
* 獲取已下載的文件大小
*/
- (NSInteger)fileLengthForPath:(NSString *)path {
NSInteger fileLength = 0;
NSFileManager *fileManager = [[NSFileManager alloc] init]; // default is not thread safe
if ([fileManager fileExistsAtPath:path]) {
NSError *error = nil;
NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];
if (!error && fileDict) {
fileLength = [fileDict fileSize];
}
}
return fileLength;
}
這樣我們用AFNetworking也實現了『離線斷點下載』的需求。