美文网首页
AFNetworking 源码阅读

AFNetworking 源码阅读

作者: 老黑来袭 | 来源:发表于2021-02-23 14:29 被阅读0次

一、AFNetworking 五大模块

1、网络通信模块
NSURLSession
2、网络监听模块
Reachability
3、序列化/反序列化模块
Serialization
4、安全传输模块
Security
5、UIKit的扩展
UIKit

二、网络通信模块

AFHTTPSessionManager、AFURLSessionManager , AFHTTPSessionManager是继承自AFURLSessionManager所以我们先来看AFURLSessionManager

@interface AFURLSessionManager : NSObject 
<
NSURLSessionDelegate, 
NSURLSessionTaskDelegate, 
NSURLSessionDataDelegate,  // 遵循了 NSURLSession的各种协议以来处理请求的各种状态、请求、取消、暂停、进度等等
NSURLSessionDownloadDelegate, 
NSSecureCoding, 
NSCopying
>

-AFURLSessionManager 属性
网上搜了一张图片


image.png

-AFURLSessionManager方法

///---------------------
/// @name Initialization
///---------------------

/**
 Creates and returns a manager for a session created with the specified configuration. This is the designated initializer.

 @param configuration The configuration used to create the managed session.

 @return A manager for a newly-created session.
 */
- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;

configuration 默认为 defaultSessionConfiguration
1.这个方法初始化了一个operationQueue 并且设置最大并发量 = 1
2.初始化了一个默认的安全策略
3.网络状态单例持有
4.初始化一个NSLock
5.初始化存储每个任务代理的字典

取消会话,cancelPendingTasks 为 YES 则立即取消所有task,NO 则完成所有任务之后再取消会话
resetSession 是否将会话置为nil
/**
 Invalidates the managed session, optionally canceling pending tasks and optionally resets given session.
 
 @param cancelPendingTasks  Whether or not to cancel pending tasks.
 @param resetSession        Whether or not to reset the session of the manager.
 */
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks resetSession:(BOOL)resetSession;

/**
这个方法给task设置上传下载进度和完成/失败的回调为一个对象

 Creates an `NSURLSessionDataTask` with the specified request.

 @param request The HTTP request for the request.
 @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
 @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
 @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
                               uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
                             downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
                            completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject,  NSError * _Nullable error))completionHandler;

创建一个本地文件上传的task并和上面一样设置一个代理对象
///---------------------------
/// @name Running Upload Tasks
///---------------------------

/**
 Creates an `NSURLSessionUploadTask` with the specified request for a local file.

 @param request The HTTP request for the request.
 @param fileURL A URL to the local file to be uploaded.
 @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
 @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.

 @see `attemptsToRecreateUploadTasksForBackgroundSessions`
 */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
                                         fromFile:(NSURL *)fileURL
                                         progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
                                completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError  * _Nullable error))completionHandler;
和上面一样只不过文件类型不一样 这里是一个 NSData 
/**
 Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.

 @param request The HTTP request for the request.
 @param bodyData A data object containing the HTTP body to be uploaded.
 @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
 @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.
 */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
                                         fromData:(nullable NSData *)bodyData
                                         progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
                                completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;

创建一个下载任务并设置代理进度回调
/**
 Creates an `NSURLSessionUploadTask` with the specified streaming request.

 @param request The HTTP request for the request.
 @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
 @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.
 */
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
                                                 progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
                                        completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;

AFHTTPSessionManager

AFHTTPSessionManager 继承自 AFURLSessionManager
-属性

属性 baseUrl 是 readonly 说明是初始化之后就不可在改变的相当于域名我们会定义一些baseurl 省的最后请求的时候拼接的前面那一部分。但是要注意 baseUrl要以 '/' 结尾

// 请求序列化 
@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;

// 响应序列化 
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;

-方法
还有一堆构造方法

/**
 Creates and returns an `AFHTTPSessionManager` object.
 */
+ (instancetype)manager;

/**
 Initializes an `AFHTTPSessionManager` object with the specified base URL.

 @param url The base URL for the HTTP client.

 @return The newly-initialized HTTP client
 */
- (instancetype)initWithBaseURL:(nullable NSURL *)url;

/**
 Initializes an `AFHTTPSessionManager` object with the specified base URL.

 This is the designated initializer.

 @param url The base URL for the HTTP client.
 @param configuration The configuration used to create the managed session.

 @return The newly-initialized HTTP client
 */
- (instancetype)initWithBaseURL:(nullable NSURL *)url
           sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;


-请求方法

GET 请求是向服务端发起请求数据,用来获取或查询资源信息 
POST 请求是向服务端发送数据的,用来更新资源信息,它可以改变数据的种类等资源 
PUT 请求和POST请求很像,都是发送数据的,但是PUT请求不能改变数据的种类等资源,它只能修改内容 
DELETE 请求就是用来删除某个资源的 
PATCH 请求和PUT请求一样,也是用来进行数据更新的,它是HTTP verb推荐用于更新的 

1.GET

- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
                            parameters:(nullable id)parameters
                               headers:(nullable NSDictionary <NSString *, NSString *> *)headers
                              progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
                               success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                               failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;

其他请求大同小异不列举

AFURLSessionManagerTaskDelegate

看名字就知道是某一个请求的代理封装 NSURLSessionTaskDelegate、NSURLSessionDataDelegate、NSURLSessionDownloadDelegate 的封装并且调用初始化时传过来的回调,他也只是承担了一部分由AFURLSessionManager转化过来的代理处理

AFNetworkReachabilityManager

没怎么看这个的源码,这是一个独立的网络监听,可获取单例也可自己创建。

可以监听这几个状态
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
    AFNetworkReachabilityStatusUnknown          = -1,
    AFNetworkReachabilityStatusNotReachable     = 0,
    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    AFNetworkReachabilityStatusReachableViaWiFi = 2,
};

AFURLRequestSerialization

队发起请求的配置封装timeout、headers、等等的配置。

AFURLResponseSerialization

封装了几种网络请求response类型,json、xml


image.png

相关文章

网友评论

      本文标题:AFNetworking 源码阅读

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