AFNetworking 3.x源码学习(网络会话模块主流程梳理)

AF的源码主要分为以下五个部分,最近主要研读了核心模块--网络会话的代码,做一做笔记,方便以后查阅。

源码结构.jpg

很多公司的网络模块都是基于AF封装的,如果发HTTP请求的话,我们直接使用的是AFHTTPSessionManager。它是继承AFURLSessionManager类的,只是对其做了一层HTTP请求的封装,方便直接使用。先来一张示意图,了解以下大概的流程,以免待会看代码看到懵逼。


流程图

接下来直接看GET请求的API实现:

- (NSURLSessionDataTask *)GET:(NSString *)URLString
                   parameters:(id)parameters
                     progress:(void (^)(NSProgress * _Nonnull))downloadProgress
                      success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
                      failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{

    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
                                                        URLString:URLString
                                                       parameters:parameters
                                                   uploadProgress:nil
                                                 downloadProgress:downloadProgress
                                                          success:success
                                                          failure:failure];

    [dataTask resume];

    return dataTask;
}

这个方法里面没有做什么实际的事情,直接进到dataTaskWithHTTPMethod方法。这里留个标记A

  • 标记A
- (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
{
    NSError *serializationError = nil;
    //调用self.requestSerializer生成requets
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
    if (serializationError) {
        if (failure) {
            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
                failure(nil, serializationError);
            });
        }

        return nil;
    }

    __block NSURLSessionDataTask *dataTask = nil;
    //根据request生成dataTask
    dataTask = [self dataTaskWithRequest:request
                          uploadProgress:uploadProgress
                        downloadProgress:downloadProgress
                       completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
        if (error) {
            if (failure) {
                failure(dataTask, error);
            }
        } else {
            if (success) {
                success(dataTask, responseObject);
            }
        }
    }];

    return dataTask;
}

可以很明显的看到该方法的大体逻辑,就是使用Manager的requestSerializer根据传进来的url,parameters等参数生成request,然后使用该request生成NSURLSessionDataTask返回。这里主要是两个方法的调用,即生成request的方法:

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                 URLString:(NSString *)URLString
                                parameters:(nullable id)parameters
                                     error:(NSError * _Nullable __autoreleasing *)error;

和生成NSURLSessionDataTask的方法:

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
                               uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
                             downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
                            completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject,  NSError * _Nullable error))completionHandler;

我们先来看看request的生成方法实现,这里留个标记1,待会会回过头来讲:

  • 标记1
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                 URLString:(NSString *)URLString
                                parameters:(id)parameters
                                     error:(NSError *__autoreleasing *)error
{
    NSParameterAssert(method);
    NSParameterAssert(URLString);

    NSURL *url = [NSURL URLWithString:URLString];

    NSParameterAssert(url);

    NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    mutableRequest.HTTPMethod = method;

    for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
        if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
            [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
        }
    }
    //拼接HTTP头和参数
    mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];

    return mutableRequest;
}

除去断言和基础的url,request生成方法;比较有意思的是request根据keypath设置value的实现。AFHTTPRequestSerializerObservedKeyPaths是一个C函数,返回一个字符串数组。具体实现如下:

static NSArray * AFHTTPRequestSerializerObservedKeyPaths() {
    static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))];
    });

    return _AFHTTPRequestSerializerObservedKeyPaths;
}

看起来是一些方法名转成的字符串,实际上对应的是AFHTTPRequestSerializer.h文件中声明的6个属性,如下图:


头文件声明属性.jpg

全局搜一下这个函数名,可以看到其实在AFHTTPRequestSerializer的init方法中也有用到,就是KVO了自己的这几个属性,同时创建了后面需要用到的set容器mutableObservedChangedKeyPaths:

    
    self.mutableObservedChangedKeyPaths = [NSMutableSet set];
    for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
        if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
            [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
        }
    }

如果外部设置该属性为有效值的话,就将对应的属性名加入到self.mutableObservedChangedKeyPaths中,反之则移除。

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(__unused id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if (context == AFHTTPRequestSerializerObserverContext) {
        if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
            [self.mutableObservedChangedKeyPaths removeObject:keyPath];
        } else {
            [self.mutableObservedChangedKeyPaths addObject:keyPath];
        }
    }
}

那么我们回到标记1的地方,可以知道方法实现中的for循环部分,其实是将用户可能设置了的AFHTTPRequestSerializer的6个属性的值,映射到它生成的request中去,因为NSMutableURLRequest有着相同的6个属性。其实就是如果用户设置了某个属性的值,那么生成的request就使用相应的值,没有设置的话,就用系统默认值的意思。剩下这个方法,就是拼接HTTP头和参数生成request。即如下方法,这里留一个标记2:

  • 标记2
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
                               withParameters:(id)parameters
                                        error:(NSError *__autoreleasing *)error
{
    NSParameterAssert(request);

    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    //拼接HTTP头
    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
        if (![request valueForHTTPHeaderField:field]) {
            [mutableRequest setValue:value forHTTPHeaderField:field];
        }
    }];

    NSString *query = nil;
    if (parameters) {
        //看看参数是否需要用户自定义转译
        if (self.queryStringSerialization) {
            NSError *serializationError;
            query = self.queryStringSerialization(request, parameters, &serializationError);

            if (serializationError) {
                if (error) {
                    *error = serializationError;
                }

                return nil;
            }
        } else {
            //使用AFN的默认转译方式
            switch (self.queryStringSerializationStyle) {
                case AFHTTPRequestQueryStringDefaultStyle:
                    query = AFQueryStringFromParameters(parameters);
                    break;
            }
        }
    }
    
    //如果请求方式是需要将查询参数拼接到URL后面的(默认包含`GET``HEAD``DELETE`)、则拼接
    if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
        if (query && query.length > 0) {
            mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
        }
    } else {
        //否则、则放入请求体
        // #2864: an empty string is a valid x-www-form-urlencoded payload
        if (!query) {
            query = @"";
        }
        if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
            [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        }
        [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
    }

    return mutableRequest;
}

先看拼接HTTP头的部分,self.mutableHTTPRequestHeaders其实是在AFHTTPRequestSerializer的init方法里面初始化的,在这里为用户添加了诸如Accept-Language,User-Agent的默认头信息。
设置头的时候都是用的这个方法

[self setValue:userAgent forHTTPHeaderField:@"User-Agent"];

这里的一个知识点是巧用队列,避免了频繁加锁。我们知道加锁是比较重量级的操作,能不加锁就尽量不加。

- (void)setValue:(NSString *)value
forHTTPHeaderField:(NSString *)field
{
    dispatch_barrier_async(self.requestHeaderModificationQueue, ^{
        [self.mutableHTTPRequestHeaders setValue:value forKey:field];
    });
}

- (NSString *)valueForHTTPHeaderField:(NSString *)field {
    NSString __block *value;
    dispatch_sync(self.requestHeaderModificationQueue, ^{
        value = [self.mutableHTTPRequestHeaders valueForKey:field];
    });
    return value;
}

注意这里是set的时候用了异步栅栏,异步保证不需要等待就可以立即返回,栅栏保证了写的唯一性;get的时候用的同步,保证肯定取到值以后才返回。其实这一小点在《Effective Objective-C 2.0编写高质量iOS与OS X代码的52个有效方法》的第41条有详细讲解,我就不作摘抄了。
回到标记2,设置完HTTP头以后,就是参数拼接和设置。如果自定义留参数拼接,则会走自定义的;没有设置就走AF默认的拼接。拼接完以后,AF默认GET``HEAD``DELETE三个方法都是将参数拼接到URL,其余方法会将拼接参数的放到请求体中。这里我就不细讲了。现在回到标记A处,request生成好了,再看看根据request生成dataTask的方法都干了啥:

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
                               uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
                             downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
                            completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject,  NSError * _Nullable error))completionHandler {
    //生成dataTask
    __block NSURLSessionDataTask *dataTask = nil;
    url_session_manager_create_task_safely(^{
        dataTask = [self.session dataTaskWithRequest:request];
    });
    //为dataTask设置处理的代理对象
    [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];

    return dataTask;
}

注意的是,这个方法的实现是放在父类AFURLSessionManager中的。为什么生成dataTask这里要采用提交到队列这样的实现呢?

static void url_session_manager_create_task_safely(dispatch_block_t block) {
    if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) {
        // Fix of bug
        // Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8)
        // Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093
        dispatch_sync(url_session_manager_creation_queue(), block);
    } else {
        block();
    }
}

查看Issue才知道,原来是因为在iOS8以下的系统中,系统方法dataTaskWithRequest:生成dataTask时,默认是并发实现的,所以会导致taskIdentifier不唯一,那么dataTask的completionHandlers回调就会出现混乱。可以看到AF是判断系统版本,如果低于iOS8,则将生成dataTask的操作提交到到一个自己创建的串行队列中去,由此保证taskIdentifier的唯一性。
self.session是在manager的init方法中初始化的:

- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
    ...
    self.operationQueue = [[NSOperationQueue alloc] init];
    self.operationQueue.maxConcurrentOperationCount = 1;

    self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];

    ...
}

代码我没有拷全,主要看session的初始化部分,将NSURLSession的代理设置为了manager,代理方法回调队列为自定义的队列,且最大并发操作数设置为了1,即为串行。关于为什么这样做,在AF的Github的Issue中也有人提过类似问题,看大神们的讨论好像都是在说这个属性命名有问题,不应该叫operationQueue这个名字,它不是一个操作队列,只是代理NSURLSession代理方法的回调队列。反正我是没有看到相关的正面回答。个人猜测是为了让代理方法串行回调,防止数据混乱。

  • 这里我们注意一个小点,所有的dataTask都是通过self.session生成的,说明所有的dataTask共用了同一个NSURLSession,那么这么做的好处是什么?其实总结起来就是一句话:共享的Session将会复用TCP的连接,而如果每次都新建Session的操作将导致每次的网络请求都开启一个TCP的三次握手。这里有篇文章说的比较详细。

接下来我们再看看为dataTask绑定deleagte对象的方法中做了什么:

- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask
                uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
              downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
             completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
    AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:dataTask];
    delegate.manager = self;
    delegate.completionHandler = completionHandler;
    
    //设置每个task的Description
    dataTask.taskDescription = self.taskDescriptionForSessionTasks;
    //将delegate映射到字典中保存
    [self setDelegate:delegate forTask:dataTask];

    delegate.uploadProgressBlock = uploadProgressBlock;
    delegate.downloadProgressBlock = downloadProgressBlock;
}

大体就是将每个task跟AFURLSessionManagerTaskDelegate对象绑定,将传进来的那些回调block都赋值给了delegate对象,后续的回调都由delegate来发起。这里有几个小点需要留意一下:

  • 设置task的taskDescription时,实际上取的是该对象的地址。
  • taskIdentifier作key,delegate作object,映射到了self.mutableTaskDelegatesKeyedByTaskIdentifier字典中。映射的操作加了锁。(为什么映射的设置和获取操作没有使用上面说到的队列派发,而使用了NSLock的锁呢?这点暂时还没有想明白。)
  • delegate的manager属性引用了AFURLSessionManager对象,方便后续能够取到manager的responseSerializer处理响应内容。同时为了避免循环引用,delegate对manager的引用是弱引用。

至此,所有的正向操作都已经完成了,dataTask已经生成好返回了。接下来就是NSURLSession的代理方法回调处理。如果将NSURLSession的代理方式实现也写在manager当中的话,manager的职责就太繁杂了,没有遵循单一职责的编程原则。所以才有了AFURLSessionManagerTaskDelegate这个类,manager只负责代理方法的转发,具体的实现都放在了AFURLSessionManagerTaskDelegate里。

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

AFURLSessionManagerTaskDelegate中的代理方法实现:

- (void)URLSession:(__unused NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
    __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;
    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;
    }

    if (self.downloadFileURL) {
        userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
    } else if (data) {
        userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
    }

    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;
            responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError];

            if (self.downloadFileURL) {
                responseObject = self.downloadFileURL;
            }

            if (responseObject) {
                userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
            }

            if (serializationError) {
                userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
            }

            dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
                if (self.completionHandler) {
                    self.completionHandler(task.response, responseObject, serializationError);
                }

                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
                });
            });
        });
    }
}

这里就用到了前面说过的弱引用Manager,然后是一系列的data拷贝和错误处理。最后的回调为什么要放在组里面,如果有知道的,还请留言指教一下。需要注意的是接收到通知后进行的操作跟发通知的操作在同一线程。在AF中通知的发送都是在主线程,那么如果需要监听通知做一些耗时操作的话,最好自己提交到其他线程。
至此,网络会话的主体流程就梳理完了。这次只是研读了核心模块的主要流程,以后有时间还会细细研读其他模块或者其他第三方库。溜了,溜了。。。

溜了


参考资料

https://www.jianshu.com/p/dfd3ae145a68
https://www.jianshu.com/p/1ce820dc4112

你可能感兴趣的:(AFNetworking 3.x源码学习(网络会话模块主流程梳理))