AFNetworking源碼分析

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];
                });
            });
        });
    }
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,646評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,595評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,560評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,035評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,814評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,224評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,301評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,444評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,988評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,804評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,998評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,544評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,237評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,665評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,927評論 1 287
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,706評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,993評論 2 374

推薦閱讀更多精彩內容