iOS Source Completion Plan--AFNetworking 3.1.0 Source Reading

Keywords: iOS network github Attribute

See the source code for AFNetworking.
The fourth source code, for the time being, is also the last one in the direction of iOS, and is ready to take advantage of the hot Internet protocol.

Catalog

  • Dead work

  • functional module

  • AFURLSessionManager/AFHTTPSessionManager

    • Core code
    • Some interesting things
      • When listening for attributes, you can use NSStringFromSelector(@selector(xxx)) to automatically prompt.
      • Functional AIP Layering
      • How to Prevent block Loop Reference
      • Converting NSURLSession agents into block s
      • Eliminate compiler clang warning
      • A Simple and Regular Writing Method
      • How to read only to the outside and read and write to the inside
  • AFNetworkReachabilityManager

    • Core code
      • Four network states
      • Start pause
      • Callback block for state change
    • Knowledge points
      • Selection of FOUNDATION_EXPORT and UIKIT_EXTERN
      • .#if - #esle - #endif
      • Registered Key Value Dependency
  • AFSecurityPolicy

    • Core code
      • How does the. cer file work in iOS
      • Three verification modes
    • Knowledge points
      • _ Require_Quiet Judgment
  • AFHTTPRequestSerializer

  • AFHTTPResponseSerializer

    • Core code
      • AFURLResponseSerialization Protocol and Its Decoding Method
    • Knowledge points
      • Application of Protocol
      • How to return two NSError s in a method
      • NSIndexSet object
      • The images returned by the server are compressed
  • Reference material

Dead work

GitHub

Use Version 3.1.0

PODS:
  - AFNetworking (3.1.0):
    - AFNetworking/NSURLSession (= 3.1.0)
    - AFNetworking/Reachability (= 3.1.0)
    - AFNetworking/Security (= 3.1.0)
    - AFNetworking/Serialization (= 3.1.0)
    - AFNetworking/UIKit (= 3.1.0)
  - AFNetworking/NSURLSession (3.1.0):
    - AFNetworking/Reachability
    - AFNetworking/Security
    - AFNetworking/Serialization
  - AFNetworking/Reachability (3.1.0)
  - AFNetworking/Security (3.1.0)
  - AFNetworking/Serialization (3.1.0)
  - AFNetworking/UIKit (3.1.0):
    - AFNetworking/NSURLSession

DEPENDENCIES:
  - AFNetworking

SPEC CHECKSUMS:
  AFNetworking: 5e0e199f73d8626b11e79750991f5d173d1f8b67

PODFILE CHECKSUM: 75e1e619317fd130ee494d35ddff3d9c614c4390

COCOAPODS: 1.3.1

It's recommended to read NSURLSession before looking at AFN.

Otherwise, I would not feel the greatness of AFN.

"iOS Foundation Completion Plan in-depth--Overview of Network Module NSURLSession"

functional module


In addition to these four service modules, the UIKit folder is basically an extension of various UI controls.

AFURLSessionManager/AFHTTPSessionManager

AFURLSession Manager process

It undertakes the main network transmission tasks and implements most of the proxy methods of NSURLSession.

  • Core code

Can move: iOS Source Completion Plan - AFNetworking(1)

Some interesting things

  • When listening for attributes, you can use NSStringFromSelector(@selector(xxx)) to automatically prompt.

Because the attribute itself has the same name as its get method, it can reduce the probability of error.

[self.uploadProgress addObserver:self
                          forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
                             options:NSKeyValueObservingOptionNew
                             context:NULL];
  • Functional AIP Layering

AFURLSession Manager implements all NSURLSession Delegates.
At the same time, some of the agents that need to deal with complex logic are passed to AFURLSession Manager Task Delegate.
Make the code clearer and the logic clearer.
It should be noted that the AFURLSession Manager Task Delegate is completely wrapped in the AFURLSession Manager and its presence is fully felt by the outside world. But it can also do data processing, this architecture design is really admirable.
In addition, there is a good hierarchy between AFURLSession Manager and AFHTTPSession Manager.
You can use AFURLSession Manager alone for network sessions, or you can better use AFURLSession Manager for HTTP requests through AFHTTPSession Manager.

  • How to Prevent block Loop Reference

Actually, I heard a few years ago that AFN can prevent circular references, but I haven't looked at it.
Looking for it today, it seems that there is no code for it.
So I guess the reason why circular references do not occur now is that AFN is used as a singleton and self does not hold each other.

Post a code from someone else's previous post:
//Rewrite setCompletion Block
- (void)setCompletionBlock:(void (^)(void))block {
    [self.lock lock];
    if (!block) {
        [super setCompletionBlock:nil];
    } else {
        __weak __typeof(self)weakSelf = self;
        [super setCompletionBlock:^ {
            __strong __typeof(weakSelf)strongSelf = weakSelf;

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
            //See if there is a custom completion group, otherwise use the AF group
            dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group();
            //See if there is a custom completion queue, otherwise use the main queue
            dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue();
#pragma clang diagnostic pop
            
            //Call the set Block in this group and queue
            dispatch_group_async(group, queue, ^{
                block();
            });

            //Place nil at the end to prevent circular references
            dispatch_group_notify(group, url_request_operation_completion_queue(), ^{
                [strongSelf setCompletionBlock:nil];
            });
        }];
    }
    [self.lock unlock];
}

  • Converting NSURLSession agents into block s

To be honest, I don't pause much.
Personally, block s are supposed to be controlled, and NSURLSession agents add up to at least twenty or thirty.
If it comes to this order of magnitude of data transfer, it's really better to use proxy, forgive me.

  • Eliminate compiler clang warning

Wgnu can be replaced by other specific commands

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
#pragma clang diagnostic pop
  • A Simple and Regular Writing Method

Reasonable. I really saw you for the first time.

`A ?: B = A ? A : B`
  • How to read only to the outside and read and write to the inside
.h in
@property (readonly, nonatomic, strong, nullable) NSURL *baseURL;
.m in
@property (readwrite, nonatomic, strong) NSURL *baseURL;

AFNetworkReachabilityManager

AFN is responsible for the network state module. In different network states, it can monitor, or query in real time, and it needs to be turned on or off manually.

  • Four network states

Unknown, No Network, Operator Network, WiFi Network

  • Start pause
  • Callback block for state change

Not much code, details can be consulted iOS Source Completion Plan - AFNetworking (II)

Knowledge points

  • Selection of FOUNDATION_EXPORT and UIKIT_EXTERN

You can define constants instead of macros

FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;

Some people say that if the document is based on FOUNDATION, use the former and vice versa.
Both can replace # define and are more efficient by comparing constants by address (that is, by directly comparing them with==).

  • #if - #esle - #endif
#ifdef __IPHONE_11_0
    //Corresponding code
#endif

The same is true with ordinary if-else, and the benefit is whether it will be compiled at the compilation stage.
However, if - esle - ENDIF cannot be used to judge a dynamic grammar.

  • Registered Key Value Dependency

A Cold Door Method for KVO

+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
    
    if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
        
        return [NSSet setWithObject:@"networkReachabilityStatus"];
    }

    return [super keyPathsForValuesAffectingValueForKey:key];
}

Trigger key listening when the return value is changed
That is to say, when the network Reachability Status changes, the KVO listening of reachable/reachableViaWWAN/reachableViaWiFi will be triggered.

AFSecurityPolicy

Verification module responsible for network security policy (certificate)

Core code

  • How does the. cer file work in iOS

The whole validation is based on SecTrustRef, and the relationship between. cer files is roughly as follows:
NSData Format Certificate==> SecCertificateRef==> SecTrustRef Object
SecTrustRef, on the other hand, is a structure with at least certificates and public keys inside.

  • Three verification modes

The concrete logic of unconditional trust server's certificate, public key validation and certificate validation.

In fact, the whole module has not much to study, because they are fixed methods. You can only write like that.~
But look at it line by line. How iOS certificates are verified is also good.
Interested can refer to iOS Source Completion Plan - AFNetworking(3)

Knowledge points

  • _ Require_Quiet Judgment

Macros _Require_Quiet and _Require_noErr_Quiet
Actually, the function is similar to if-esle, but it can jump from multiple entries to a unified exit, and the correlation function _Require_XXX basically means this. Write a few small methods, want to see their own can copy run


#import <AssertMacros.h>


    //The assertion that it is false executes the third action, throws an exception, and jumps to _out
    __Require_Action(1, _out, NSLog(@"immediate jump"));
    //If the assertion is true, go down or jump out
    __Require_Quiet(1,_out);
    NSLog(@"111");
    
    //If you don't comment, you jump right out of here.
//    __Require_Quiet(0,_out);
//    NSLog(@"222");
    
    //If there are no errors, that is NO, continue executing
    __Require_noErr(NO, _out);
    NSLog(@"333");
    
    //If there is an error, that is YES, jump to _out, and throw an exception location
    __Require_noErr(YES, _out);
    NSLog(@"444");
_out:
    NSLog(@"end");

2018-05-17 14:18:12.656703+0800 AFNetWorkingDemo[4046:313255] 111
2018-05-17 14:18:12.656944+0800 AFNetWorkingDemo[4046:313255] 333
AssertMacros: YES == 0 ,  file: /Users/kiritoSong/Desktop/Blog/KTAFNetWorkingDemo/AFNetWorkingDemo/AFNetWorkingDemo/ViewController.m, line: 39, value: 1
2018-05-17 14:18:12.657097+0800 AFNetWorkingDemo[4046:313255] end

In this way, we have three ways of judging.
1. if-else of Ordinary Logic
2. Compiler-level # if - #esle - #endif
3. Macro Judgment of _Require_XXX with Multi-entrance and Unified Export

AFHTTPRequestSerializer

Initialization of the NSMutableURLRequest object for network requests
And automatic configuration of request header, request body, parameters and uploaded files
Thousands of lines of code, long. But reading it will benefit a lot.

  • Flow chart


    Flow chart of AFHTTP Request Serializer

The process seems simple, but there are many things to implement.
It includes how to convert the parameter dictionary into strings and translate them, how to do the piecewise splicing copy of files, how to integrate the request body files into the request medium, and so on.

Detailed API s can be consulted: iOS Source Completion Plan - AFNetworking (IV)

AFHTTPResponseSerializer

Look at the content of AFURLResponseSerialization.
Responsible for formatting the response body returned by the server after the successful network request

Core code

AFURLResponseSerialization Protocol and Its Decoding Method

- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
                           data:(nullable NSData *)data
                          error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;

For different parsers (JSON/XML/PList, etc.), this protocol is implemented.
At the end of the request, help AFURLSession Manager parse the response volume obtained.

Detailed API s can be moved: iOS Source Completion Plan - AFNetworking (V)

Knowledge points

  • Application of Protocol
    • By letting multiple objects follow the same protocol, we can replace inheritance when decoupling, and then overload the parent method. Make a protocol, return different results.
    • In the case of multi-person collaboration, it is also a common way to improve development efficiency by agreeing on protocols and then transferring them to other business implementations.
  • How to return two NSError s in a method

You can specify a major error in a nested way, such as NSUnderlying ErrorKey.

  • NSIndexSet object

NSIndexSet is a digital version of NSSet.
A set of unsigned integers and internal elements have uniqueness.

NSMutableIndexSet *indexSetM = [NSMutableIndexSet indexSet];
[indexSetM addIndex:19];
[indexSetM addIndex:4];
[indexSetM addIndex:6];
[indexSetM addIndex:8];
[indexSetM addIndexesInRange:NSMakeRange(20, 10)];

[indexSetM enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%lu",idx);
}];

//2016-08-10 11:39:00.826 qikeyunDemo[3765:100078] 4
//2016-08-10 11:39:00.827 qikeyunDemo[3765:100078] 6
//2016-08-10 11:39:00.827 qikeyunDemo[3765:100078] 8
//2016-08-10 11:39:00.827 qikeyunDemo[3765:100078] 19
//2016-08-10 11:39:00.827 qikeyunDemo[3765:100078] 20
//2016-08-10 11:39:00.828 qikeyunDemo[3765:100078] 21
//2016-08-10 11:39:00.828 qikeyunDemo[3765:100078] 22
//2016-08-10 11:39:00.828 qikeyunDemo[3765:100078] 23
//2016-08-10 11:39:00.828 qikeyunDemo[3765:100078] 24
//2016-08-10 11:39:00.828 qikeyunDemo[3765:100078] 25
//2016-08-10 11:39:00.828 qikeyunDemo[3765:100078] 26
//2016-08-10 11:39:00.828 qikeyunDemo[3765:100078] 27
//2016-08-10 11:39:00.828 qikeyunDemo[3765:100078] 28
//2016-08-10 11:39:00.829 qikeyunDemo[3765:100078] 29

Internal elements are sorted automatically

  • The images returned by the server are compressed

Pictures returned by the server and bitmap information need to be decompressed.
The function of bitmap is to deliver UI Image to UI Image View.
If there is no bitmap, it will be decompressed automatically once in the main thread.

Reference material

What exactly did AFNetworking do? (end)
iOS Source Completion Plan - AFNetworking(1)
iOS Source Completion Plan - AFNetworking (II)
iOS Source Completion Plan - AFNetworking (III)
iOS Source Completion Program--AFNetworking (IV)
iOS Source Completion Plan - AFNetworking (V)
Horses on the road A God who wrote many source code interpretations

Posted by Azarian on Sat, 18 May 2019 02:24:41 -0700