AFNetworking源碼探究(一) —— 基本介紹

版本記錄

版本號(hào) 時(shí)間
V1.0 2018.02.27

前言

我們做APP發(fā)起網(wǎng)絡(luò)請(qǐng)求,都離不開(kāi)一個(gè)非常有用的框架AFNetworking,可以說(shuō)這個(gè)框架的知名度已經(jīng)超過(guò)了蘋果的底層網(wǎng)絡(luò)請(qǐng)求部分,很多人可能不知道蘋果底層是如何發(fā)起網(wǎng)絡(luò)請(qǐng)求的,但是一定知道AFNetworking,接下來(lái)幾篇我們就一起詳細(xì)的解析一下這個(gè)框架。

整體了解

首先我們就看一下AFN在GitHub中的地址 —— AFN

下面是AFN的一個(gè)作者

下面看一下框架的基本結(jié)構(gòu)


安裝

安裝有兩種方式CocoaPodsCarthage

  • CocoaPods

使用CocoaPods,用下面命令安裝CocoaPods

$ gem install cocoapods

構(gòu)建AFNetworking 3.0.0+需要CocoaPods 0.39.0+版本

按照下面方式修改Podfile

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'

target 'TargetName' do
pod 'AFNetworking', '~> 3.0'
end

運(yùn)行下面代碼,安裝

$ pod install
  • Carthage

使用Homebrew以及下面的命令行安裝Carthage

$ brew update
$ brew install carthage

在Cartfile文件中,指定要集成到xcode項(xiàng)目中的AFN版本

github "AFNetworking/AFNetworking" ~> 3.0

運(yùn)行carthage構(gòu)建庫(kù),并將構(gòu)建好的AFNetworking.framework拖動(dòng)到xcode的項(xiàng)目中。


版本需求


詳細(xì)架構(gòu)

下面我們就看一下AFN的詳細(xì)架構(gòu)。

NSURLSession

  • AFURLSessionManager
  • AFHTTPSessionManager

Serialization

  • <AFURLRequestSerialization>
    • AFHTTPRequestSerializer
    • AFJSONRequestSerializer
    • AFPropertyListRequestSerializer
  • <AFURLResponseSerialization>
    • AFHTTPResponseSerializer
    • AFJSONResponseSerializer
    • AFXMLParserResponseSerializer
    • AFXMLDocumentResponseSerializer (macOS)
    • AFPropertyListResponseSerializer
    • AFImageResponseSerializer
    • AFCompoundResponseSerializer

Additional Functionality

  • AFSecurityPolicy
  • AFNetworkReachabilityManager

也可以參考下面的圖


使用

1. AFURLSessionManager

AFURLSessionManager基于遵循<NSURLSessionTaskDelegate>,<NSURLSessionDataDelegate>,<NSURLSessionDownloadDelegate><NSURLSessionDelegate>的指定NSURLSessionConfiguration對(duì)象創(chuàng)建和管理NSURLSession對(duì)象。

Creating a Download Task - 創(chuàng)建一個(gè)Download Task

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil 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];

Creating an Upload Task - 創(chuàng)建一個(gè)Upload Task

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask resume];

Creating an Upload Task for a Multi-Part Request, with Progress - 為具有進(jìn)度的多部分請(qǐng)求創(chuàng)建上傳任務(wù)

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
              uploadTaskWithStreamedRequest:request
              progress:^(NSProgress * _Nonnull uploadProgress) {
                  // This is not called back on the main queue.
                  // You are responsible for dispatching to the main queue for UI updates
                  dispatch_async(dispatch_get_main_queue(), ^{
                      //Update the progress view
                      [progressView setProgress:uploadProgress.fractionCompleted];
                  });
              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                  } else {
                      NSLog(@"%@ %@", response, responseObject);
                  }
              }];

[uploadTask resume];

Creating a Data Task - 創(chuàng)建數(shù)據(jù)任務(wù)

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@ %@", response, responseObject);
    }
}];
[dataTask resume];

2. Request Serialization

請(qǐng)求序列化器從URL字符串創(chuàng)建請(qǐng)求,將參數(shù)編碼為查詢字符串或HTTP正文。

NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};

Query String Parameter Encoding - 查詢字符串參數(shù)編碼

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

URL Form Parameter Encoding - URL表單參數(shù)編碼

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3

JSON Parameter Encoding - JSON參數(shù)編碼

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/json

{"foo": "bar", "baz": [1,2,3]}

3. Network Reachability Manager

AFNetworkReachabilityManager監(jiān)控域的可達(dá)性,以及WWAN和WiFi網(wǎng)絡(luò)接口的地址。

  • 不要使用Reachability來(lái)確定是否應(yīng)發(fā)送原始請(qǐng)求。
    • 你應(yīng)該嘗試發(fā)送它。
  • 您可以使用Reachability來(lái)確定何時(shí)應(yīng)該自動(dòng)重試請(qǐng)求。
    • 雖然它可能仍然失敗,但是連接可用的可達(dá)性通知是重試某件事的好時(shí)機(jī)。
  • 網(wǎng)絡(luò)可達(dá)性是確定請(qǐng)求失敗原因的有用工具。
    • 在網(wǎng)絡(luò)請(qǐng)求失敗后,告訴用戶他們處于離線狀態(tài)比向他們提供更加技術(shù)性但準(zhǔn)確的錯(cuò)誤(如“請(qǐng)求超時(shí)”)要好。

可以參考 WWDC 2012 session 706, "Networking Best Practices.

Shared Network Reachability

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

4. Security Policy

AFSecurityPolicy通過(guò)安全連接評(píng)估針對(duì)固定的X.509證書(shū)和公鑰的服務(wù)器信任。

將固定的SSL證書(shū)添加到您的應(yīng)用程序有助于防止中間人攻擊和其他漏洞。 強(qiáng)烈建議處理敏感客戶數(shù)據(jù)或財(cái)務(wù)信息的應(yīng)用程序通過(guò)HTTPS連接路由所有通信,并配置啟用SSL pinning

Allowing Invalid SSL Certificates - 允許無(wú)效的SSL證書(shū)

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production

單元測(cè)試

AFNetworking在Tests子目錄中包含一套單元測(cè)試。 這些測(cè)試可以運(yùn)行,只需在您想測(cè)試的平臺(tái)框架上執(zhí)行測(cè)試操作即可。

后記

本篇作為AFNetworking的介紹篇,內(nèi)容主要來(lái)自GitHub,比較簡(jiǎn)單。后面會(huì)對(duì)源碼進(jìn)行深入分析,感興趣的可以關(guān)注我~~~

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

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

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