AFNetworking使用及見解

AFNetworking簡單使用

AFNetworking我們在開發(fā)中經(jīng)常會使用到,我這里就根據(jù)自己的使用來說下個人的認(rèn)識。首先說下AFNetworking的使用:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject = %@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"error = %@",error);
        }
    }];

上面這種是最簡單的使用
我們再來看下如果用系統(tǒng)的NSURLSession來做的話是什么樣的,如下

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    request.HTTPMethod = @"GET";
    [request setValue:@"application/json" forHTTPHeaderField:@"Conten-Type"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(error){
            NSLog(@"error = %@",error);
        }else{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"dic = %@",dic);
        }
    }];
    [task resume];

從調(diào)用步驟上看,使用AFNetworking比我們直接使用系統(tǒng)的NSURLSession要方便點多,那AFNetworking內(nèi)部到底是如何做的呢?下面我們就通過源碼看下。

AFNetworking組成部分

-NSURLSession :網(wǎng)絡(luò)處理,請求、上傳、下載
-Reachability:網(wǎng)絡(luò)可達(dá)性,檢測網(wǎng)絡(luò)變化
-Security:完全相關(guān),處理請求時的簽名等處理
-Serialization:序列化,分為request和response

AFNetworking內(nèi)部實現(xiàn)

我們主要看下NSURLSession這部分是如何設(shè)計和實現(xiàn)的。
NSURLSession由兩個類組成:AFHTTPSessionManagerAFURLSessionManager。

AFHTTPSessionManager

繼承于AFURLSessionManager,是AFURLSessionManager進(jìn)行了二次封裝。主要是我們常用的get、post請求。

AFHTTPSessionManager

繼承于NSObject,是對NSURLSession的封裝。封裝了請求、上傳、下載等相關(guān)方法。
上面的各種方法都是通過NSURLSession對應(yīng)的delegate方式來實現(xiàn)的。
關(guān)鍵的一個類AFURLSessionManagerTaskDelegate,這個是用來記錄上傳時相關(guān)NSURLSessionTask信息的,具體定義如下:

@interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
- (instancetype)initWithTask:(NSURLSessionTask *)task;
@property (nonatomic, weak) AFURLSessionManager *manager;
@property (nonatomic, strong) NSMutableData *mutableData;
@property (nonatomic, strong) NSProgress *uploadProgress;
@property (nonatomic, strong) NSProgress *downloadProgress;
@property (nonatomic, copy) NSURL *downloadFileURL;
@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock;
@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock;
@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler;
@end

當(dāng)用戶調(diào)用請求接口時,會創(chuàng)建AFURLSessionManagerTaskDelegate對象,然后添加到NSMutableDictionary對象mutableTaskDelegatesKeyedByTaskIdentifier中,用于后面不同sessionTask的區(qū)分。
當(dāng)數(shù)據(jù)接收完成對應(yīng)代碼:

//代理
- (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];
    }

    if (self.taskDidComplete) {
        self.taskDidComplete(session, task, error);
    }
}

請求完成后,清空task數(shù)據(jù)

- (void)removeDelegateForTask:(NSURLSessionTask *)task {
    NSParameterAssert(task);

    [self.lock lock];
    [self removeNotificationObserverForTask:task];
    [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)];
    [self.lock unlock];
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容