AFNetworking解析(一)

AFURLSessionManager 请求关键类
AFHTTPSessionManager 请求包装类
AFNetworkReachabilityManager 网络状态类
AFSecurityPolicy 加密类
AFURLRequestSerialization 序列化类
AFURLResponseSerialization 反序列化类

AFHTTPSessionManager

继承自AFURLSessionManager
添加了属性

@property (readonly, nonatomic, strong, nullable) NSURL *baseURL;
@property (nonatomic, strong) AFHTTPRequestSerializer  * requestSerializer;
@property (nonatomic, strong) AFHTTPResponseSerializer  * responseSerializer;
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;

//初始化方法都会调用此方法

  - (instancetype)initWithBaseURL:(NSURL *)url
           sessionConfiguration:(NSURLSessionConfiguration *)configuration
{
    //初始化AFHTTPSessionManager
    self = [super initWithSessionConfiguration:configuration];
    if (!self) {
        return nil;
    }
    //确保baseURL路径的终端斜线,以便NSURL + URLWithString:relativeToURL:按预期工作
    // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
      if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
          url = [url URLByAppendingPathComponent:@""];
     }
      self.baseURL = url;
      self.requestSerializer = [AFHTTPRequestSerializer serializer];
      self.responseSerializer = [AFJSONResponseSerializer serializer];
      return self;
  }

get请求

- (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
{
    //生成task Get方式 调用 AFURLSessionManager方法
    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
                                                        URLString:URLString
                                                       parameters:parameters
                                                   uploadProgress:nil
                                                 downloadProgress:downloadProgress
                                                          success:success
                                                          failure:failure];
    //开始请求
    [dataTask resume];
    return dataTask;
}

AFURLSessionManager类

参数

@property (readonly, nonatomic, strong) NSURLSession *session;//包装session
@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;//回调队列
@property (nonatomic, strong) id  responseSerializer;//反序列化对象
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;//网络状态
@property (readonly, nonatomic, strong) NSArray  *tasks;//任务
@property (readonly, nonatomic, strong) NSArray  *dataTasks;
@property (readonly, nonatomic, strong) NSArray  *uploadTasks;
@property (readonly, nonatomic, strong) NSArray  *downloadTasks;
@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;//请求完成队列
@property (nonatomic, strong, nullable) dispatch_group_t completionGroup;//请求完成队列组
@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions;
//初始调用返回“nil”时是否尝试重试创建后台会话的上传任务。 默认为“NO”。

初始化方法

- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
    self = [super init];
    if (!self) {
        return nil;
    }
    //没有传configuration就用默认defaultSessionConfiguration
    if (!configuration) {
        configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    }
    //把configuration赋给AFURLSessionManager
    self.sessionConfiguration = configuration;
    //代理回调的队列,并发数为1
    self.operationQueue = [[NSOperationQueue alloc] init];
    self.operationQueue.maxConcurrentOperationCount = 1;
    //NSURLSession的委托委托给AFURLSessionManager对象,做进一步处理
    self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];
    //转码
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    //默认安全策略
    self.securityPolicy = [AFSecurityPolicy defaultPolicy];
\#if !TARGET_OS_WATCH
    //网络状况
    self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];#endif
    //存放delegate的字典
    self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];
    //保护存放delegate的字典
    self.lock = [[NSLock alloc] init];
    self.lock.name = AFURLSessionManagerLockName;
    //置空所有运行中的task 防止后台回来重新初始化session
    [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];
        }
    }];
    return self;
}
  1. 初始化配置和代理回调队列,新建NSURLSession
  2. 初始化反序列化
  3. 默认安全策略,网络状态初始化
  4. mutableTaskDelegatesKeyedByTaskIdentifier字典存放task和对应delegate
  5. self.lock 用来给mutableTaskDelegatesKeyedByTaskIdentifier操作加锁
  6. 置空所有运行中的task 防止后台回来重新初始化session

task的委托相关操作
//取出task的委托

- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task {
    NSParameterAssert(task);
    //按照task.taskIdentifier从mutableTaskDelegatesKeyedByTaskIdentifier字典中取出委托
    AFURLSessionManagerTaskDelegate *delegate = nil;
    [self.lock lock];
    delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)];
    [self.lock unlock];
    return delegate;
}

//添加自定义委托AFURLSessionManagerTaskDelegate

- (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委托对象,初始化data,progress,给progress配置取消,暂停,恢复方法,用来操作task
    AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:dataTask];
    //弱引用
    delegate.manager = self;
    //回调
    delegate.completionHandler = completionHandler;
    //这个taskDescriptionForSessionTasks用来发送开始和挂起通知的时候会用到,就是用这个值来Post通知,来两者对应
    dataTask.taskDescription = self.taskDescriptionForSessionTasks;
    //保存delegate
    [self setDelegate:delegate forTask:dataTask];
    //上传进度赋值给TaskDelegate
    delegate.uploadProgressBlock = uploadProgressBlock;
    //下载进度赋值给TaskDelegate
    delegate.downloadProgressBlock = downloadProgressBlock;
}

AFURLSessionManagerTaskDelegate类

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

方法中实例化,作为AFURLSessionManager的回调使用

//添加自定义委托AFURLSessionManagerTaskDelegate
- (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委托对象,初始化data,progress,给progress配置取消,暂停,恢复方法,用来操作task
    AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:dataTask];
    //弱引用
    delegate.manager = self;
    //回调
    delegate.completionHandler = completionHandler;
    //这个taskDescriptionForSessionTasks用来发送开始和挂起通知的时候会用到,就是用这个值来Post通知,来两者对应
    dataTask.taskDescription = self.taskDescriptionForSessionTasks;
    //保存delegate
    [self setDelegate:delegate forTask:dataTask];
    //上传进度赋值给TaskDelegate
    delegate.uploadProgressBlock = uploadProgressBlock;
    //下载进度赋值给TaskDelegate
    delegate.downloadProgressBlock = downloadProgressBlock;
}

其中

    [self setDelegate:delegate forTask:dataTask];

加锁操作可变字典mutableTaskDelegatesKeyedByTaskIdentifier,把task.taskIdentifier和delegate作为键值对存进去
实现代码

- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
            forTask:(NSURLSessionTask *)task
{
    NSParameterAssert(task);
    NSParameterAssert(delegate);
    //锁,保护mutableTaskDelegatesKeyedByTaskIdentifier字典
    [self.lock lock];
    //可变字典,用来保存task的delegate,键为task生成时的taskIdentifier
   self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
    //添加取消,恢复通知
    [self addNotificationObserverForTask:task];
    [self.lock unlock];
}

你可能感兴趣的:(AFNetworking解析(一))