美文网首页
AFNetworking - AFURLSessionManag

AFNetworking - AFURLSessionManag

作者: ASkyWatcher | 来源:发表于2020-06-16 15:41 被阅读0次

    AFURLSessionManager这个类是AFNetworking最核心的类,它的任务就是管理会话,响应会话中的每一个任务

    我们首先来梳理一下一次完整的网络请求及其响应,看看它是走哪些方法,按照什么顺序来走,我们就看一次最简单的GET请求

    首先,我们还记得在最外层AFHTTPSessionManager类中发起了请求任务

    __block NSURLSessionDataTask *dataTask = nil;
        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);
                }
            }
        }];
    

    它调用了它的父类也就是AFURLSessionManager的任务创建方法

    - (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 {
        
        //根据请求创建一个任务
        NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:request];
        //把创建的每一个任务交给一个AFURLSessionManagerTaskDelegate类来管理
        [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];
    
        return dataTask;
    }
    

    addDelegateForDataTask方法为每一个任务创建一个任务代理类,由它来全权独立管理每个任务的状态,进度和完成的回调,并且把它和每个任务进行一一对应,以便在会话中能正确响应每个任务的代理回调方法

    这段代码我认为也是最能表现AFNetworking这个框架精髓的一段代码,它体现了AFNetworking的核心思想,公用session,没有必要进行多余的TCP连接,在一个会话里面创建多个任务,独立管理每个任务,这样既能节约资源也能很大程度缩短网络请求的时间,提高会话任务的效率

    - (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;
    
        //任务描述
        dataTask.taskDescription = self.taskDescriptionForSessionTasks;
        //将每一个任务和它对应的任务管理类进行键值对关系绑定
        [self setDelegate:delegate forTask:dataTask];
    
        //上传进度代码块
        delegate.uploadProgressBlock = uploadProgressBlock;
        //下载进度代码块
        delegate.downloadProgressBlock = downloadProgressBlock;
    }
    

    这里就是为任务和任务代理类关系进行绑定的方法,以任务的ID为键,AFURLSessionManagerTaskDelegate对象为值,这里还用了锁,来保证绑定过程的安全

    - (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
                forTask:(NSURLSessionTask *)task
    {
        NSParameterAssert(task);
        NSParameterAssert(delegate);
    
        //这里用锁来保证线程安全,mutableTaskDelegatesKeyedByTaskIdentifier经常需要被改动
        [self.lock lock];
        self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
        [self addNotificationObserverForTask:task];
        [self.lock unlock];
    }
    

    发起请求后首先会进行https认证,前面说的安全策略类AFSecurityPolicy就是在这里进行认证

    - (void)URLSession:(NSURLSession *)session
                  task:(NSURLSessionTask *)task
    didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
     completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
    {
        BOOL evaluateServerTrust = NO;
        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
        NSURLCredential *credential = nil;
    
        if (self.authenticationChallengeHandler) {
            id result = self.authenticationChallengeHandler(session, task, challenge, completionHandler);
            if (result == nil) {
                return;
            } else if ([result isKindOfClass:NSError.class]) {
                objc_setAssociatedObject(task, AuthenticationChallengeErrorKey, result, OBJC_ASSOCIATION_RETAIN);
                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
            } else if ([result isKindOfClass:NSURLCredential.class]) {
                credential = result;
                disposition = NSURLSessionAuthChallengeUseCredential;
            } else if ([result isKindOfClass:NSNumber.class]) {
                disposition = [result integerValue];
                NSAssert(disposition == NSURLSessionAuthChallengePerformDefaultHandling || disposition == NSURLSessionAuthChallengeCancelAuthenticationChallenge || disposition == NSURLSessionAuthChallengeRejectProtectionSpace, @"");
                evaluateServerTrust = disposition == NSURLSessionAuthChallengePerformDefaultHandling && [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
            } else {
                @throw [NSException exceptionWithName:@"Invalid Return Value" reason:@"The return value from the authentication challenge handler must be nil, an NSError, an NSURLCredential or an NSNumber." userInfo:nil];
            }
        } else {
            evaluateServerTrust = [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
        }
    
        if (evaluateServerTrust) {
            if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
                disposition = NSURLSessionAuthChallengeUseCredential;
                credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            } else {
                objc_setAssociatedObject(task, AuthenticationChallengeErrorKey,
                                         [self serverTrustErrorForServerTrust:challenge.protectionSpace.serverTrust url:task.currentRequest.URL],
                                         OBJC_ASSOCIATION_RETAIN);
                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
            }
        }
    
        if (completionHandler) {
            completionHandler(disposition, credential);
        }
    }
    

    服务器收到请求后返回数据,这时候会响应NSURLSessionDataDelegate接收返回数据的方法,这里数据可能是分多次返回,可能会响应多次

    - (void)URLSession:(NSURLSession *)session
              dataTask:(NSURLSessionDataTask *)dataTask
        didReceiveData:(NSData *)data
    {
    
        //根据任务找到对应的任务代理类
        AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
        //调用代理类的数据接收方法,和NSURLSessionDataDelegate的代理方法一致,只是在delegate里拼接可能多次返回的数据
        [delegate URLSession:session dataTask:dataTask didReceiveData:data];
        
        //收到服务器返回数据回调的代码块
        if (self.dataTaskDidReceiveData) {
            self.dataTaskDidReceiveData(session, dataTask, data);
        }
    }
    

    AFURLSessionManagerTaskDelegate中的- (void)URLSession:dataTask:didReceiveData:方法

    - (void)URLSession:(__unused NSURLSession *)session
              dataTask:(__unused NSURLSessionDataTask *)dataTask
        didReceiveData:(NSData *)data
    {
        //下载进度设置
        self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive;
        self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived;
        //拼接数据
        [self.mutableData appendData:data];
    }
    

    接收服务器数据完成后,接着会响应NSURLSessionDataDelegate中的- (void)URLSession:task:didCompleteWithError:方法

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

    再继续调用delegate中的该方法,请求服务器数据完成回调

    - (void)URLSession:(__unused NSURLSession *)session
                  task:(NSURLSessionTask *)task
    didCompleteWithError:(NSError *)error
    {
        //如果有认证质询错误也要返回
        error = objc_getAssociatedObject(task, AuthenticationChallengeErrorKey) ?: error;
        //强引用,防止被提前释放
        __strong AFURLSessionManager *manager = self.manager;
    
        __block id responseObject = nil;
    
        //创建一个信息字典
        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.
            //这时mutableData已经没有用,清空
            self.mutableData = nil;
        }
    
    #if AF_CAN_USE_AT_AVAILABLE && AF_CAN_INCLUDE_SESSION_TASK_METRICS
        if (@available(iOS 10, macOS 10.12, watchOS 3, tvOS 10, *)) {
            //任务度量(包含请求响应时间等度量)
            if (self.sessionTaskMetrics) {
                userInfo[AFNetworkingTaskDidCompleteSessionTaskMetrics] = self.sessionTaskMetrics;
            }
        }
    #endif
        //下载数据存储的位置
        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];
                    });
                });
            });
        }
    }
    

    相关文章

      网友评论

          本文标题:AFNetworking - AFURLSessionManag

          本文链接:https://www.haomeiwen.com/subject/vlrgtktx.html