AFNetworking 實現(xiàn)了文件的上傳/下載,以及斷點(diǎn)續(xù)傳。
內(nèi)部封裝了 NSURLSession ,替代了之前的 NSURLConnection。
關(guān)于斷點(diǎn)續(xù)傳:把下載文件放到temp里,每間隔一段時間并用文件的形式存儲下載完的數(shù)據(jù)字節(jié)數(shù),當(dāng)resume的時候,會查詢到之前下載到進(jìn)度,如1000字節(jié),并放在HTTP 頭部的 range 字段,如:1000-3000,這樣服務(wù)器就會返回1000字節(jié)后的數(shù)據(jù);斷點(diǎn)上傳道理類似;
AFURLSessionManager 會創(chuàng)建并管理一個NSURLSession 對象,這是一次會話,而這個會話可以創(chuàng)建多個task任務(wù),每個任務(wù)可以執(zhí)行上傳下載等操作;
依賴的包有:
- Security.framework
- MobileCoreServices.framework
- SystemConfiguration.framework
- UIKit.framework
對于 NSURLSessionDataTask,官方解釋說,這沒有其他任何的附加功能,只是為了區(qū)別和上傳下載的字面意思。但是這個任務(wù)可以用來請求一些html頁面等等;
// 創(chuàng)建session配置:如 認(rèn)證機(jī)制,緩存,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];
//創(chuàng)建downloadtask
//progress:進(jìn)度信息,會不斷進(jìn)行回調(diào)
//destination:指定下載完的文件存儲位置
//completionHandler:執(zhí)行完畢回調(diào)
_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);
}];
// 開啟任務(wù),必須調(diào)用,否則不執(zhí)行
[_downloadTask resume];
//掛起任務(wù)
// [_downloadTask suspend];
// 創(chuàng)建 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;
//創(chuàng)建下載任務(wù);
//在修復(fù)bug之前,異步執(zhí)行任務(wù),修復(fù)bug后直接執(zhí)行 block
url_session_manager_create_task_safely(^{
downloadTask = [self.session downloadTaskWithRequest:request];
});
//為 task 添加代理,此代理為 task 執(zhí)行以下操作:進(jìn)度處理,目標(biāo)文件處理回調(diào),處理完成回調(diào);
[self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
return downloadTask;
}
AFURLSessionManagerTaskDelegate:
這個類的作用就是為 downloadTask 服務(wù),如進(jìn)度回調(diào)/設(shè)置文件最終存儲位置/執(zhí)行任務(wù)完成回調(diào)(completionHandler)/恢復(fù)下載/掛起任務(wù)
- (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];
//設(shè)置代理需要服務(wù)的對象:SessionManager
delegate.manager = self;
//代理為 task 執(zhí)行‘完成回調(diào)’blok
delegate.completionHandler = completionHandler;
if (destination) {
// 重新封裝 destination ,根據(jù) destination 返回url再把文件轉(zhuǎn)到這個url(這個session參數(shù)沒用到???);
delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session,
NSURLSessionDownloadTask *task,
NSURL *location)
{
return destination(location, task.response);
};
}
downloadTask.taskDescription = self.taskDescriptionForSessionTasks;
//添加代理 ,delegate 處理進(jìn)度
[self setDelegate:delegate forTask:downloadTask];
//設(shè)置進(jìn)度回調(diào)
delegate.downloadProgressBlock = downloadProgressBlock;
}
//存儲 delegate,并設(shè)置 Progress 屬性 以及相關(guān)回調(diào)
- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
forTask:(NSURLSessionTask *)task
{
NSParameterAssert(task);
NSParameterAssert(delegate);
/*
sessionManager 可以創(chuàng)建多個任務(wù),是1對多點(diǎn)關(guān)系
所以同時添加多個task的時候,下面操作可能會導(dǎo)致線程不安全,需要加鎖;
*/
[self.lock lock];
// sessionManager 把taskDelegate 以字典方式存儲 key:delegate唯一標(biāo)識 value:delegate
self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
//設(shè)置 progress 相關(guān)屬性和操作
[delegate setupProgressForTask:task];
[self addNotificationObserverForTask:task];
[self.lock unlock];
}
/**
uploadProgress downloadProgress 負(fù)責(zé)存儲進(jìn)度屬性以及task相關(guān)操作:
設(shè)置uploadProgress 和 downloadProgress 取消操作 暫停操作 恢復(fù)下載上傳
監(jiān)聽 uploadProgress / downloadProgress
*/
- (void)setupProgressForTask:(NSURLSessionTask *)task {
__weak __typeof__(task) weakTask = task;
//獲取下載或者上傳任務(wù)的總字節(jié)數(shù)大?。挥脕碛嬎惝?dāng)前進(jìn)度(ios7之前步兼容,iOS (7.0 and later))
self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
self.downloadProgress.totalUnitCount = task.countOfBytesExpectedToReceive;
//允許取消 task
[self.uploadProgress setCancellable:YES];
//取消回調(diào),需把task轉(zhuǎn)成strong,以保證再task在取消前不被釋放掉
[self.uploadProgress setCancellationHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask cancel];
}];
//允許暫停,以下設(shè)置類似取消操作
[self.uploadProgress setPausable:YES];
[self.uploadProgress setPausingHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask suspend];
}];
//恢復(fù)上傳
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];
}];
}
/** 監(jiān)聽下載 uploadProgress downloadProgress 的 fractionCompleted(百分比) 屬性
實際上修改 downloadProgress/uploadProgress 的 totalUnitCount 或者 completedUnitCount 屬性
就會自動計算 fractionCompleted 的值;
所以在回調(diào)中直接取 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];
}
//添加監(jiān)聽resume 和suspend,以便接收delegate發(fā)送的通知
- (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];
}
需要實現(xiàn)幾個代理:
- NSURLSessionDelegate,
- NSURLSessionTaskDelegate,
- NSURLSessionDataDelegate,
- NSURLSessionDownloadDelegate
這個方法很關(guān)鍵,用于累加返回的data數(shù)據(jù):
/**
更新下載進(jìn)度:
下載過程會多次調(diào)用這個方法
每次調(diào)用會接收一段數(shù)據(jù)
totalBytesWritten:到目前為止接收到的數(shù)據(jù)總大小(累計接收到的數(shù)據(jù));
totalBytesExpectedToWrite:總的下載數(shù)據(jù)大小;
totalBytesWritten/totalBytesExpectedToWrite:已完成進(jìn)度百分比;
*/
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
// 傳遞給代理,記錄下載進(jìn)度
if (delegate) {
[delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
}
if (self.downloadTaskDidWriteData) {
self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
}
// 下載完成回調(diào)
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
// 調(diào)用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];
//只看到發(fā)送錯誤信息通知,未找到在哪處理錯誤信息
if (error) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
}
return;
}
}
// 通知 delegate 把下載的臨時文件轉(zhuǎn)移到指定地點(diǎn)
if (delegate) {
[delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location];
}
}
// sessionTaskDelegate
// 完成傳輸任務(wù)
- (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];
// 移除代理以及監(jiān)聽
[self removeDelegateForTask:task];
}
// 需要手動調(diào)用 setTaskDidCompleteBlock ,才會執(zhí)行 taskDidComplete,如果沒有手動設(shè)置,則在代理里執(zhí)行commectionHandler
if (self.taskDidComplete) {
self.taskDidComplete(session, task, error);
}
}
相應(yīng)的會調(diào)用delegate中的幾個方法,主要用delegate來輔助執(zhí)行:
- (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
//用于記錄下載進(jìn)度:
- (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;
}
//用于記錄下載進(jìn)度:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
self.downloadProgress.totalUnitCount = expectedTotalBytes;
self.downloadProgress.completedUnitCount = fileOffset;
}
//下載完成回調(diào)
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
NSError *fileManagerError = nil;
self.downloadFileURL = nil;
// 把下載到臨時文件移動到指定地點(diǎn)
if (self.downloadTaskDidFinishDownloading) {
// 獲取用戶指定的目標(biāo) url
self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
if (self.downloadFileURL) {
[[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError];
//只看到發(fā)送錯誤信息通知,未找到在哪處理錯誤信息
if (fileManagerError) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
}
}
}
}
最后一步,執(zhí)行completionHandler:
completionHandler 交給 delegate 來處理:
/**
下載完成回調(diào)
執(zhí)行 complectionHandler
并把返回結(jié)果打包發(fā)送通知
*/
- (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
// 執(zhí)行重要操作之前需要把 weak 類型轉(zhuǎn)成 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(累計下載完的數(shù)據(jù))拷貝到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 回調(diào)里已經(jīng)記錄了 downloadFileURL 變量
優(yōu)先記錄 downloadFileURL 其次記錄data,因為存儲url數(shù)據(jù)量小
*/
if (self.downloadFileURL) {
userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
} else if (data) {
userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
}
//如果下載出錯,則 執(zhí)行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 數(shù)據(jù)
task.response:存儲:url 類型 長度 文件名 加密信息
*/
responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError];
// 如果下載數(shù)據(jù)成功,即 downloadFileURL 不為空,優(yōu)先使用 url ,如果沒有 url,再使用 responseObject
if (self.downloadFileURL) {
responseObject = self.downloadFileURL;
}
if (responseObject) {
userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
}
if (serializationError) {
userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
}
/**
把任務(wù)添加到 completionQueue 中;
并發(fā)執(zhí)行
*/
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
// 執(zhí)行 completionHandler ,傳遞解密后的數(shù)據(jù),或者url ,以及錯誤信息
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, serializationError);
}
// 把數(shù)據(jù)打包發(fā)送通知,用于用戶自己擴(kuò)展
// 例如下載操作和 completionHandler 不在一個類中,可以接收這個通知
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
});
}
}