您的位置:首页 > 理论基础 > 计算机网络

AFNetWorking(3.0)源码分析(二)——AFURLSessionManager

2016-07-19 08:04 447 查看
AFNetworking是基于NSURLSession实现的。回想一下NSURLSession的使用方式:

创建NSURLSessionConfig对象

用之前创建的NSURLSessionConfig对象创建配置NSURLSession对象。

用NSURLSession对象创建对应的task对象 并用resume方法执行之。

用delegate方法或completion block 响应网络事件及数据。

对应于每次网络会话(这里可以简单理解为一个网页),对应一个NSURLSession对象,而每个会话,可以生成若干task对象用于数据的交互。

而在AFNet中, AFURLSessionManager作为核心类,封装并提供了上述网络交互功能。

AFURLSessionManager组成

AFNet运用了组合的设计模式,将不同功能搭建成AFURLSessionManager的功能。

AFURLSessionManager的主要属性:

/**
The managed session.
*/
@property (readonly, nonatomic, strong) NSURLSession *session;

/**
The operation queue on which delegate callbacks are run.
*/
@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;

/**
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.

@warning `responseSerializer` must not be `nil`.
*/
@property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer;

///-------------------------------
/// @name Managing Security Policy
///-------------------------------

/**
The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
*/
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;

#if !TARGET_OS_WATCH
///--------------------------------------
/// @name Monitoring Network Reachability
///--------------------------------------

/**
The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
*/
@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
#endif

///----------------------------
/// @name Getting Session Tasks
///----------------------------

/**
The data, upload, and download tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray <NSURLSessionTask *> *tasks;

/**
The data tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray <NSURLSessionDataTask *> *dataTasks;

/**
The upload tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray <NSURLSessionUploadTask *> *uploadTasks;

/**
The download tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray <NSURLSessionDownloadTask *> *downloadTasks;

///-------------------------------
/// @name Managing Callback Queues
///-------------------------------

/**
The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
*/
@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;

/**
The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
*/
@property (nonatomic, strong, nullable) dispatch_group_t completionGroup;


AFNet的注释很详细,其属性可以作如下分类

AFURLSessionManager所管理的Session对象

@property (readonly, nonatomic, strong) NSURLSession *session;

delegate所返回的NSOperationQueue

@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;

解析网络返回数据的对象(遵循AFURLResponseSerialization协议)

@property (nonatomic, strong) id responseSerializer;

用于处理网络连接安全处理策略的AFSecurityPolicy对象

@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;

用于检测网络数据的AFNetworkReachabilityManager对象

@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;

当前的Session task

*tasks;

*dataTasks;

*uploadTasks;

*downloadTasks;

设置Call back队列

在这里除了能设置Session的completion block外(默认为main block),还可以设置completion group。

看过这些分类,是不是觉得AFURLSessionManager也不是多么复杂了?确实,AFNet本就是一套简洁的网络框架,功能强大而结构清晰。

下面,我们就一起看一看,利用AFURLSessionManager是如何完成一次简单的网络请求的。

运用AFURLSessionManager完成网络请求

运用AFRULSessionManager获取网络数据,仅需如下几个步骤:

// step1. 初始化AFURLSessionManager对象
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

// step2. 获取AFURLSessionManager的task对象
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"Get Net data success!");
}
}];

// step3. 发动task
[dataTask resume];


OK,简单的三步,就完成了对网络数据的请求。

下面我们就一步步分析,这三步背后AFNet的源代码是如何实现的。

初始化AFURLSessionManager

要进行网络请求,第一步就是初始化AFURLSessionManager,调用函数

- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration


该函数很简单,只有一个NSURLSessionConfiguration用来配置AFURLSessionManager所管理的NSURLSession对象。

它的实现代码如下:

(instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
self = [super init];
if (!self) {
return nil;
}
// =============== 设置NSURLSession ===============
// 若configuration为nil,则采用默认defaultSessionConfiguration

if (!configuration) {
configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
}

self.sessionConfiguration = configuration;
// session 的delegate callback queue, 最大并发为1
self.operationQueue = [[NSOperationQueue alloc] init];
self.operationQueue.maxConcurrentOperationCount = 1;
// 初始化所管理的session
self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];

// =============== 设置response 数据序列化 ===============
self.responseSerializer = [AFJSONResponseSerializer serializer];

// =============== 设置网络安全策略 ===============
self.securityPolicy = [AFSecurityPolicy defaultPolicy];

// =============== 设置网络状态监控Manager(注意这里是一个全局单例实现) ===============
#if !TARGET_OS_WATCH
self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
#endif
// =============== 设置存储NSURL task与AFURLSessionManagerTaskDelegate的词典(重点,在AFNet中,每一个task都会被匹配一个AFURLSessionManagerTaskDelegate 来做task的delegate事件处理) ===============
self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];

// =============== 设置AFURLSessionManagerTaskDelegate 词典的锁,确保词典在多线程访问时的线程安全===============
self.lock = [[NSLock alloc] init];
self.lock.name = AFURLSessionManagerLockName;

// =============== 为所管理的session的所有task设置完成块(这里不是很明白,既然是初始化函数,那么应该没有任何task在运行才是,怎么需要在这里设置完成块呢???)===============
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
for (NSURLSessionDataTask *task in dataTasks) {
[self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil];
}

for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
[self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil];
}

for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
[self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil];
}
}];
// =============== 返回初始化好的self ===============
return self;
}


这就是AFURLSessionManager的初始化函数,主要是对其属性进行初始化,要注意的是它的私有属性

@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier;

@property (readwrite, nonatomic, strong) NSLock *lock;


AFURLSessionManager会为每一个所管理的task对应创建一个AFURLSessionManagerTaskDelegate对象,Manager会交ManagerTaskDelegate对象由来具体处理各个task事物,从而实现了同一个AFURLSessionManager对多个task的管理。

生成AFURLSessionManager的task对象

当初始化好AFURLSessionManager后,就需要获取一个代表我们当前网络请求的task了:

/**
Creates an `NSURLSessionDataTask` with the specified request.

@param request The HTTP request for the request.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject,  NSError * _Nullable error))completionHandler;


当然还可以获取download task 和upload task, 这里我们仅分析最简单的data task。

其实现如下:

return [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:completionHandler];


仅一行代码,调用自身另一方法:

- (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 {

__block NSURLSessionDataTask *dataTask = nil;
url_session_manager_create_task_safely(^{
dataTask = [self.session dataTaskWithRequest:request];
});

[self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];

return dataTask;
}


上述方法完成了两件事情:

1. 生成一个data task对象,并返回。

2. 为该data task对象生成一个匹配的AFURLSessionManagerTaskDelegate对象,并关联之。

对于功能1,没什么多说的,就是这里AFNet为了避免iOS 8.0以下版本中偶发的taskIdentifiers不唯一的bug,AFNet使用了

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


函数创建task对象。

其实现应该是因为iOS 8.0以下版本中会并发地创建多个task对象,而同步有没有做好,导致taskIdentifiers 不唯一…

对于功能二,AFNet为每一个task生成对应的task delegate对象,我们则应该重点了解一下。

- (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对象
AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
// AFURLSessionManagerTaskDelegate与AFURLSessionManager建立相互关系
delegate.manager = self;
// 设置AF delegate的完成块为用户传入的完成块
delegate.completionHandler = completionHandler;
// 设置dataTask的taskDescription
dataTask.taskDescription = self.taskDescriptionForSessionTasks;
// ***** 将AF delegate对象与 dataTask建立关系
[self setDelegate:delegate forTask:dataTask];
// 设置AF delegate的上传进度,下载进度块。
delegate.uploadProgressBlock = uploadProgressBlock;
delegate.downloadProgressBlock = downloadProgressBlock;
}


AFNet通过封装AFURLSessionManagerTaskDelegate对象,对每个task 进行管理,而AFURLSessionManager仅需要管理建立task 与AF delegate的词典即可,实现了AFURLSessionManager功能的下放。

那么我们这里重点看一下,AF delegate与task是如何建立关系的:

[self setDelegate:delegate forTask:dataTask];


实现:

- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
forTask:(NSURLSessionTask *)task
{
NSParameterAssert(task);
NSParameterAssert(delegate);
// 加锁,确保词典的线程安全
[self.lock lock];
// 将AF delegate放入以taskIdentifier标记的词典中(同一个NSURLSession中的taskIdentifier是唯一的)
self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
// 为AF delegate 设置task 的progress监听
[delegate setupProgressForTask:task];
[self addNotificationObserverForTask:task];
// 词典操作完毕,解锁
[self.lock unlock];
}


AFURLSessionManager会将每个AF delegate放入其词典中,同时,AF delegate会监听每个task的进度,这是通过

[delegate setupProgressForTask:task];


实现的。我们继续看 AF delegate 是如何监听task的各种进度的:

#pragma mark - NSProgress Tracking

- (void)setupProgressForTask:(NSURLSessionTask *)task {
__weak __typeof__(task) weakTask = task;

self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
self.downloadProgress.totalUnitCount = task.countOfBytesExpectedToReceive;
[self.uploadProgress setCancellable:YES];
[self.uploadProgress setCancellationHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask cancel];
}];
[self.uploadProgress setPausable:YES];
[self.uploadProgress setPausingHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask suspend];
}];
if ([self.uploadProgress respondsToSelector:@selector(setResumingHandler:)]) {
[self.uploadProgress setResumingHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask resume];
}];
}

[self.downloadProgress setCancellable:YES];
[self.downloadProgress setCancellationHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask cancel];
}];
[self.downloadProgress setPausable:YES];
[self.downloadProgress setPausingHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask suspend];
}];

if ([self.downloadProgress respondsToSelector:@selector(setResumingHandler:)]) {
[self.downloadProgress setResumingHandler:^{
__typeof__(weakTask) strongTask = weakTask;
[strongTask resume];
}];
}

// 这里为什么要用NSStringFromSelector 而不直接使用NSString???
[task addObserver:self
forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))
options:NSKeyValueObservingOptionNew
context:NULL];
[task addObserver:self
forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))
options:NSKeyValueObservingOptionNew
context:NULL];

[task addObserver:self
forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))
options:NSKeyValueObservingOptionNew
context:NULL];
[task addObserver:self
forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToSend))
options:NSKeyValueObservingOptionNew
context:NULL];

[self.downloadProgress addObserver:self
forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
options:NSKeyValueObservingOptionNew
context:NULL];
[self.uploadProgress addObserver:self
forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
options:NSKeyValueObservingOptionNew
context:NULL];
}


上面的代码可以分为两个部分,

1. 设置AF delegate的uploadProgress 和 downloadProgress。(注意为了防止对block对象截取产生的循环引用,将传入的task设置为了weak。但是这里的循环引用在哪里呢??? 其实这里鉴于block所造成的一系列循环引用的问题,AFNet采取了一种防御式编程的方法,对于没有必要在block中进行强引用的变量,一律采用弱引用。并且,当task置为nil后,block也没有理由继续strong引用task变量)

2. 利用KVO, 监听task属性及uploadProgress,downloadProgress属性的变化,进一步监听task的数据传输进程。

看到了KVO,那我们就直接看其对应的响应函数:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([object isKindOfClass:[NSURLSessionTask class]]) {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) {
self.downloadProgress.completedUnitCount = [change[@"new"] longLongValue];
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))]) {
self.downloadProgress.totalUnitCount = [change[@"new"] longLongValue];
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
self.uploadProgress.completedUnitCount = [change[@"new"] longLongValue];
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToSend))]) {
self.uploadProgress.totalUnitCount = [change[@"new"] longLongValue];
}
}
else if ([object isEqual:self.downloadProgress]) {
if (self.downloadProgressBlock) {
self.downloadProgressBlock(object);
}
}
else if ([object isEqual:self.uploadProgress]) {
if (self.uploadProgressBlock) {
self.uploadProgressBlock(object);
}
}
}


很简单,当监控的Task属性改变时,同时改变由AF delegate所管理持有的Progress对象的属性。

同时,当AF delegate的Progress对象属性改变时,调用对应的progress block。

NSURLSessionDelegate 的响应

因为AFURLSessionManager所管理的NSURLSession对象的delegate被设置为AFURLSessionManager自身,因此所有的NSURLSessionDelegate回调方法的目的地都是AFURLSessionManager,而AFURLSessionManager又会根据是否需要具体处理,会将属于AF delegate要响应的delegate,传递到对应的AF delegate去。

AFURLSessionManager 和 AFURLSessionManagerTaskDelegate 相应的delegate回调方法如下:

AFURLSessionManager 需要处理的NSURLSessionDelegate:



AFURLSessionManagerTaskDelegate 需要处理的NSURLSessionDelegate:



当AFURLSessionManager 觉得应该有AF delegate来处理该事件时,会取出对应task的delegate,并将该事件原封不动的传递到delegate。

其实细看AF delegate所实现的NSURLSessionDelegate也不多,仅三条:

-URLSession:task:didCompleteWithError:
-URLSession:dataTask:didReceiveData:
-URLSession:downloadTask:didFinishDownloadingToURL:


可以看出,属于AF task delegate处理的回调,两条是对于completion的处理,另一条则是对于每个task,分别接受并记录其receive data。

而AFURLSessionManager对于NSSession的回调处理相对简单,不外乎两步:

1. 如果有对应的user block,则将当前NSSession block传递至user block(此处可能会利用user block的返回值,来继续下一步操作)。

2. 如果需要AF task delegate处理,则将该回调事件传给相应的AF task delegate。

我们可以看下面几个例子:

- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
newRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLRequest *))completionHandler
{
NSURLRequest *redirectRequest = request;
// step1. 看是否有对应的user block
if (self.taskWillPerformHTTPRedirection) {
redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request);
}

if (completionHandler) {
// step2. 运用user block返回值或是原始值,使NSSession事件继续
completionHandler(redirectRequest);
}
}


- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
// step1. 应交由AF task delegate处理的事件,取出对应AF task delegate,
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];

// delegate may be nil when completing a task in the background
if (delegate) {
// step2. 将事件交由AF task delegate处理
[delegate URLSession:session task:task didCompleteWithError:error];
// NOTE: 此处是session task最终的回调函数,task不会再返回任何信息。因此删除对应的AF task delegate
[self removeDelegateForTask:task];
}
// step3. 若有对应的user block,则调用之
if (self.taskDidComplete) {
self.taskDidComplete(session, task, error);
}
}


AFURLSessionManager 与 AFURLSessionManagerTaskDelegate 的分工

到这里我们可以想一想,既然NSURLSession的delegate是AFURLSessionManager对象,那么为什么不在AFURLSessionManager中处理所有的事件回调,搞出来一个AFURLSessionManagerTaskDelegate干什么?

我们知道,NSURLSession的回调有很多,而当我们启动一个task,真正想要获取的信息是什么呢?就是网络请求最终所返回的数据(我所进行的网络操作成功或是失败,服务器为我返回的数据)呗! 其它的回调,什么认证质询,task需要新的body stream,什么request即将重定向, 统统都是浮云,都是为了我们能够最终获取到服务器返回的数据所服务的。

另外我们也想要知道我们的网络请求的进度。

总结为两点:

1. 获取最终返回数据

2. 获知当前请求的进度

于是,AFNetWorking 便在纷繁复杂的回调处理中,特意抽象出AFURLSessionManagerTaskDelegate,用于应付网络返回数据的处理(包括保存中间值,序列化返回值,错误处理)和网络请求进度。

这样做可以使代码结构更分明,逻辑更清晰。

这在AFURLSessionManagerTaskDelegate的声明中也可以看出一二, 其属性按功能分类就两种,一种用来保存服务器返回数据及completion回调,另一种就是反应当前网络处理进度:

@interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
@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


结语

以上就是对于AFURLSessionManager处理网络请求的一个大概分析,下一章中我们会对AFURLSessionManager中所用的编程技巧,以及值得注意的地方,做一番终结。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络 AFNet