Files
knowledge-kit/Chapter1 - iOS/1.138.md
2026-02-22 22:12:36 +01:00

5.2 KiB

AFNetworking Source Code Explanation

Structure

The core contains 5 functional modules:

  • Network communication module (AFURLSessionManager, AFHTTPSessionManager)
  • Network reachability module (Reachability)
  • Network security policy module (Security)
  • Network request/response serialization/deserialization module (Serialization)
  • UIKit extensions for iOS (UIKit)

AF is a wrapper around NSURLSession, so the core class AFURLSessionManager is a wrapper for NSURLSession. The other four modules support networking (request/response serialization, HTTPS security authentication, UIKit extensions).

AFHTTPSessionManager inherits from AFURLSessionManager. Most network requests are made using AFHTTPSessionManager, but this class itself does not directly perform the networking; it wraps and delegates request logic to its superclass AFURLSessionManager or other classes.

Example: GET request

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]init];

[manager GET:@"https://somehost.com/goods" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

}];

Create a manager by calling the initializer. Let's see what it does:

- (instancetype)init {
    return [self initWithBaseURL:nil];
}

- (instancetype)initWithBaseURL:(NSURL *)url {
    return [self initWithBaseURL:url sessionConfiguration:nil];
}

- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
    return [self initWithBaseURL:nil sessionConfiguration:configuration];
}

- (instancetype)initWithBaseURL:(NSURL *)url
           sessionConfiguration:(NSURLSessionConfiguration *)configuration
{
    self = [super initWithSessionConfiguration:configuration];
    if (!self) {
        return nil;
    }
    // If a BaseURL is provided and it does not end with "/", append "/"
    if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
        url = [url URLByAppendingPathComponent:@""];
    }

    self.baseURL = url;

    self.requestSerializer = [AFHTTPRequestSerializer serializer];
    self.responseSerializer = [AFJSONResponseSerializer serializer];

    return self;
}

All initializers eventually call the above.

Digital Certificates

Digital signatures ensure message integrity and provide authentication. Like public-key cryptography, they use a pair of keys (public and private). But in contrast, signatures are created with the private key (to generate the signature) and verified with the public key. Only the holder of the private key can create the signature, while anyone with the public key can verify it.

Public Key Infrastructure (PKI) is a set of standards and specifications to use public-key cryptography more effectively. The X.509 standard is one widely used PKI format.

Certificate Chain

CAs have hierarchical relationships. The highest-level certificate authority is usually the root CA. Lower-level certificates are signed by an upper-level CA; the root CA typically self-signs (self-signed certificate).

How do you verify that a certificate has not been tampered with? When the client connects over HTTPS, the server returns the full certificate chain. Start from the leaf certificate and use the issuer's public key to verify the digital signature of the subordinate certificate. Continue validating up the chain until you reach a trust anchor (a trusted root certificate).

Example GET request — deeper exploration

  1. Request entry point
- (NSURLSessionDataTask *)GET:(NSString *)URLString
                   parameters:(id)parameters
                      success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                      failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
  1. Create NSURLSessionDataTask
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure

What AF does compared to raw native APIs

Starting from GET/POST entry points and analyzing the source:

  • Initializes many properties
  • Adds safety measures (for example, addressing iOS 8 task identifier uniqueness issues using dispatch_sync)
  • Provides custom block-based progress callbacks that are easier to use
  • Uses decoupling to reduce complexity in main classes, making maintenance easier

AFSecurityPolicy source analysis — HTTPS authentication

https://www.jianshu.com/p/856f0e26279d

https://www.jianshu.com/u/14431e509ae8

https://blog.csdn.net/ZCMUCZX/article/details/79399517