AFNetworking 實現了文件的上傳/下載,以及斷點續傳。
內部封裝了 NSURLSession ,替代了之前的 NSURLConnection。
關于斷點續傳:把下載文件放到temp里,每間隔一段時間并用文件的形式存儲下載完的數據字節數,當resume的時候,會查詢到之前下載到進度,如1000字節,并放在HTTP 頭部的 range 字段,如:1000-3000,這樣服務器就會返回1000字節后的數據;斷點上傳道理類似;
AFURLSessionManager 會創建并管理一個NSURLSession 對象,這是一次會話,而這個會話可以創建多個task任務,每個任務可以執行上傳下載等操作;
依賴的包有:
- Security.framework
- MobileCoreServices.framework
- SystemConfiguration.framework
- UIKit.framework
對于 NSURLSessionDataTask,官方解釋說,這沒有其他任何的附加功能,只是為了區別和上傳下載的字面意思。但是這個任務可以用來請求一些html頁面等等;
// 創建session配置:如 認證機制,緩存,cookies存儲位置,超時時間等...
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://123.125.110.24/imtt.dd.qq.com/16891/97EF88D9A32972CDE911B374A46B774D.apk?mkey=58070789ffa35a8e&f=4e1d&c=0&fsname=com.tencent.WeFire_2.7.0_5477.apk&p=.apk"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
//創建downloadtask
//progress:進度信息,會不斷進行回調
//destination:指定下載完的文件存儲位置
//completionHandler:執行完畢回調
_downloadTask = [manager downloadTaskWithRequest:request
progress:^(NSProgress *downloadProgress)
{
NSLog(@"downloadProgress:%f",downloadProgress.fractionCompleted);
}
destination:^ NSURL *(NSURL *targetPath, NSURLResponse *response)
{
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:NO
error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
// 開啟任務,必須調用,否則不執行
[_downloadTask resume];
//掛起任務
// [_downloadTask suspend];
// 創建 downloadTask ,并給 downloadTask 添加代理
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
__block NSURLSessionDownloadTask *downloadTask = nil;
//創建下載任務;
//在修復bug之前,異步執行任務,修復bug后直接執行 block
url_session_manager_create_task_safely(^{
downloadTask = [self.session downloadTaskWithRequest:request];
});
//為 task 添加代理,此代理為 task 執行以下操作:進度處理,目標文件處理回調,處理完成回調;
[self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
return downloadTask;
}
AFURLSessionManagerTaskDelegate:
這個類的作用就是為 downloadTask 服務,如進度回調/設置文件最終存儲位置/執行任務完成回調(completionHandler)/恢復下載/掛起任務
- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask
progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
//設置代理需要服務的對象:SessionManager
delegate.manager = self;
//代理為 task 執行‘完成回調’blok
delegate.completionHandler = completionHandler;
if (destination) {
// 重新封裝 destination ,根據 destination 返回url再把文件轉到這個url(這個session參數沒用到???);
delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session,
NSURLSessionDownloadTask *task,
NSURL *location)
{
return destination(location, task.response);
};
}
downloadTask.taskDescription = self.taskDescriptionForSessionTasks;
//添加代理 ,delegate 處理進度
[self setDelegate:delegate forTask:downloadTask];
//設置進度回調
delegate.downloadProgressBlock = downloadProgressBlock;
}
//存儲 delegate,并設置 Progress 屬性 以及相關回調
- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
forTask:(NSURLSessionTask *)task
{
NSParameterAssert(task);
NSParameterAssert(delegate);
/*
sessionManager 可以創建多個任務,是1對多點關系
所以同時添加多個task的時候,下面操作可能會導致線程不安全,需要加鎖;
*/
[self.lock lock];
// sessionManager 把taskDelegate 以字典方式存儲 key:delegate唯一標識 value:delegate
self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
//設置 progress 相關屬性和操作
[delegate setupProgressForTask:task];
[self addNotificationObserverForTask:task];
[self.lock unlock];
}
/**
uploadProgress downloadProgress 負責存儲進度屬性以及task相關操作:
設置uploadProgress 和 downloadProgress 取消操作 暫停操作 恢復下載上傳
監聽 uploadProgress / downloadProgress
*/
- (void)setupProgressForTask:(NSURLSessionTask *)task {
__weak __typeof__(task) weakTask = task;
//獲取下載或者上傳任務的總字節數大小;用來計算當前進度(ios7之前步兼容,iOS (7.0 and later))
self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
self.downloadProgress.totalUnitCount = task.countOfBytesExpectedToReceive;
//允許取消 task
[self.uploadProgress setCancellable:YES];
//取消回調,需把task轉成strong,以保證再task在取消前不被釋放掉
[self.uploadProgress setCancellationHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask cancel];
}];
//允許暫停,以下設置類似取消操作
[self.uploadProgress setPausable:YES];
[self.uploadProgress setPausingHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask suspend];
}];
//恢復上傳
if ([self.uploadProgress respondsToSelector:@selector(setResumingHandler:)]) {
[self.uploadProgress setResumingHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask resume];
}];
}
[self.downloadProgress setCancellable:YES];
[self.downloadProgress setCancellationHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask cancel];
}];
[self.downloadProgress setPausable:YES];
[self.downloadProgress setPausingHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask suspend];
}];
if ([self.downloadProgress respondsToSelector:@selector(setResumingHandler:)]) {
[self.downloadProgress setResumingHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask resume];
}];
}
/** 監聽下載 uploadProgress downloadProgress 的 fractionCompleted(百分比) 屬性
實際上修改 downloadProgress/uploadProgress 的 totalUnitCount 或者 completedUnitCount 屬性
就會自動計算 fractionCompleted 的值;
所以在回調中直接取 fractionCompleted 即可;
*/
[self.downloadProgress addObserver:self
forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
options:NSKeyValueObservingOptionNew
context:NULL];
[self.uploadProgress addObserver:self
forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
options:NSKeyValueObservingOptionNew
context:NULL];
}
//添加監聽resume 和suspend,以便接收delegate發送的通知
- (void)addNotificationObserverForTask:(NSURLSessionTask *)task {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task];
}
需要實現幾個代理:
- NSURLSessionDelegate,
- NSURLSessionTaskDelegate,
- NSURLSessionDataDelegate,
- NSURLSessionDownloadDelegate
這個方法很關鍵,用于累加返回的data數據:
/**
更新下載進度:
下載過程會多次調用這個方法
每次調用會接收一段數據
totalBytesWritten:到目前為止接收到的數據總大小(累計接收到的數據);
totalBytesExpectedToWrite:總的下載數據大小;
totalBytesWritten/totalBytesExpectedToWrite:已完成進度百分比;
*/
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
// 傳遞給代理,記錄下載進度
if (delegate) {
[delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
}
if (self.downloadTaskDidWriteData) {
self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
}
// 下載完成回調
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
// 調用setDownloadTaskDidFinishDownloadingBlock方法才會初始化downloadTaskDidFinishDownloading
// 否則會在delegate里移動下載文件到指定位置
if (self.downloadTaskDidFinishDownloading) {
// 獲取用戶指定下載路徑
NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
if (fileURL) {
delegate.downloadFileURL = fileURL;
NSError *error = nil;
//移動文件到指定位置
[[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error];
//只看到發送錯誤信息通知,未找到在哪處理錯誤信息
if (error) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
}
return;
}
}
// 通知 delegate 把下載的臨時文件轉移到指定地點
if (delegate) {
[delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location];
}
}
// sessionTaskDelegate
// 完成傳輸任務
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
// delegate may be nil when completing a task in the background
if (delegate) {
[delegate URLSession:session task:task didCompleteWithError:error];
// 移除代理以及監聽
[self removeDelegateForTask:task];
}
// 需要手動調用 setTaskDidCompleteBlock ,才會執行 taskDidComplete,如果沒有手動設置,則在代理里執行commectionHandler
if (self.taskDidComplete) {
self.taskDidComplete(session, task, error);
}
}
相應的會調用delegate中的幾個方法,主要用delegate來輔助執行:
- (void)URLSession:(__unused NSURLSession *)session
dataTask:(__unused NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived;
self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive;
[self.mutableData appendData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
self.uploadProgress.completedUnitCount = task.countOfBytesSent;
self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
}
#pragma mark - NSURLSessionDownloadDelegate
//用于記錄下載進度:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
self.downloadProgress.totalUnitCount = totalBytesExpectedToWrite;
self.downloadProgress.completedUnitCount = totalBytesWritten;
}
//用于記錄下載進度:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
self.downloadProgress.totalUnitCount = expectedTotalBytes;
self.downloadProgress.completedUnitCount = fileOffset;
}
//下載完成回調
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
NSError *fileManagerError = nil;
self.downloadFileURL = nil;
// 把下載到臨時文件移動到指定地點
if (self.downloadTaskDidFinishDownloading) {
// 獲取用戶指定的目標 url
self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
if (self.downloadFileURL) {
[[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError];
//只看到發送錯誤信息通知,未找到在哪處理錯誤信息
if (fileManagerError) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
}
}
}
}
最后一步,執行completionHandler:
completionHandler 交給 delegate 來處理:
/**
下載完成回調
執行 complectionHandler
并把返回結果打包發送通知
*/
- (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
// 執行重要操作之前需要把 weak 類型轉成 strong,防止過程中 manager 被釋放
__strong AFURLSessionManager *manager = self.manager;
__block id responseObject = nil;
__block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
//Performance Improvement from #2672
NSData *data = nil;
// 把 mutableData(累計下載完的數據)拷貝到data,然后釋放
if (self.mutableData) {
data = [self.mutableData copy];
//We no longer need the reference, so nil it out to gain back some memory.
self.mutableData = nil;
}
/**在didFinishDownloadingToURL 回調里已經記錄了 downloadFileURL 變量
優先記錄 downloadFileURL 其次記錄data,因為存儲url數據量小
*/
if (self.downloadFileURL) {
userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
} else if (data) {
userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
}
//如果下載出錯,則 執行completionHandler block的時候傳遞錯誤信息
if (error) {
userInfo[AFNetworkingTaskDidCompleteErrorKey] = error;
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
} else {
dispatch_async(url_session_manager_processing_queue(), ^{
NSError *serializationError = nil;
/** 解密 data 數據
task.response:存儲:url 類型 長度 文件名 加密信息
*/
responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError];
// 如果下載數據成功,即 downloadFileURL 不為空,優先使用 url ,如果沒有 url,再使用 responseObject
if (self.downloadFileURL) {
responseObject = self.downloadFileURL;
}
if (responseObject) {
userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
}
if (serializationError) {
userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
}
/**
把任務添加到 completionQueue 中;
并發執行
*/
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
// 執行 completionHandler ,傳遞解密后的數據,或者url ,以及錯誤信息
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, serializationError);
}
// 把數據打包發送通知,用于用戶自己擴展
// 例如下載操作和 completionHandler 不在一個類中,可以接收這個通知
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
});
}
}