美文网首页
AFNWorking

AFNWorking

作者: OKR02 | 来源:发表于2019-06-22 19:28 被阅读0次

未完…
本文主要讲 AF3.x

AFNWorking 框架结构

AF主要模块划分如下:


AF 框架结构.png

一、AFURLSessionManager

1、AFURLSessionManager初始化

首先初始化方法

[AFHTTPSessionManager manager];
+ (instancetype)manager {
    return [[[self class] alloc] initWithBaseURL:nil];
}

它不是单例模式,而是工厂模式;是一系列的初始化。

/*
 1.初始化一个session
 2.给manager的属性设置初始值
 */
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
    self = [super init];
    if (!self) {
        return nil;
    }

    // 设置默认的configuration,配置我们的session
    if (!configuration) {
        configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    }

    // 持有configuration
    self.sessionConfiguration = configuration;

    // 设置为delegate的操作队列并发的线程数量1,也就是串行队列
    self.operationQueue = [[NSOperationQueue alloc] init];
    // 并发数设置为 1,是为了线程安全
    self.operationQueue.maxConcurrentOperationCount = 1;

    /*
     -如果完成后需要做复杂(耗时)的处理,可以选择异步队列
     -如果完成后直接更新UI,可以选择主队列
     [NSOperationQueue mainQueue]
     */
    /*
    queue
    An operation queue for scheduling the delegate calls and completion handlers. 
The queue should be a serial queue, in order to ensure the correct ordering of callbacks. 
If nil, the session creates a serial operation queue for performing all delegate method calls and completion handler calls.
     */
    self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];

    //默认为json解析(各种响应转码)
    self.responseSerializer = [AFJSONResponseSerializer serializer];

    //设置默认证书 无条件信任证书https认证(设置默认安全策略)
    self.securityPolicy = [AFSecurityPolicy defaultPolicy];

#if !TARGET_OS_WATCH
    //网络状态监听
    self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
#endif

    // 设置存储NSURL task与AFURLSessionManagerTaskDelegate的词典(重点,在AFNet中,每一个task都会被匹配一个AFURLSessionManagerTaskDelegate 来做task的delegate事件处理)
    // delegate= value taskid = key
    self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];

    // 设置AFURLSessionManagerTaskDelegate 词典的锁,确保词典在多线程访问时的线程安全
    // 使用NSLock确保线程安全
    self.lock = [[NSLock alloc] init];
    self.lock.name = AFURLSessionManagerLockName;
    //异步的获取当前session的所有未完成的task。其实讲道理来说在初始化中调用这个方法应该里面一个task都不会有
    //后台任务重新回来初始化session,可能就会有先前的任务
    //https://github.com/AFNetworking/AFNetworking/issues/3499
    [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;
}
2、NSOperationQueue
3、请求头封装
/**
 使用指定的HTTP method和URLString来构建一个NSMutableURLRequest对象实例
 如果method是GET、HEAD、DELETE,那parameter将会被用来构建一个基于url编码的查询字符串(query url)
 ,并且这个字符串会直接加到request的url后面。对于其他的Method,比如POST/PUT,它们会根
 据parameterEncoding属性进行编码,而后加到request的http body上。
 @param method request的HTTP methodt,比如 `GET`, `POST`, `PUT`, or `DELETE`. 该参数不能为空
 @param URLString 用来创建request的URL
 @param parameters 既可以对method为GET的request设置一个查询字符串(query string),也可以设置到request的HTTP body上
 @param error 构建request时发生的错误
 @return  一个NSMutableURLRequest的对象
 */
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                 URLString:(NSString *)URLString
                                parameters:(id)parameters
                                     error:(NSError *__autoreleasing *)error
{
    // 断言如果nil,直接打印出来
    NSParameterAssert(method);
    NSParameterAssert(URLString);

    // 我们传进来的是一个字符串,在这里它帮你转成url
    NSURL *url = [NSURL URLWithString:URLString];

    NSParameterAssert(url);

    NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    // 设置请求方式(get、post、put。。。)
    // 请求行
    mutableRequest.HTTPMethod = method;

    // 将request的各种属性遍历,给NSMutableURLRequest自带的属性赋值
    for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
        //给设置过得的属性,添加到request(如:timeout、cache、 policy request)
        if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
            //通过kvc动态的给mutableRequest添加value
            [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
        }
    }

    //将传入的参数进行编码,拼接到url后并返回 coount=5&start=1
    mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];
    NSLog(@"request'''''''''%@",mutableRequest);

    return mutableRequest;
}
4、请求参数封装
5、task与代理的关系

先来一张图看一下它们的关系


task与 delegate关系.png
6、manager与代理的关系

二、AFURLRequestSerialization

三、AFSecurityPolicy

四、AFImageDownloader

相关文章

网友评论

      本文标题:AFNWorking

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