当前位置:网站首页>Interpretation of afnetworking4.0 request principle
Interpretation of afnetworking4.0 request principle
2022-07-28 05:06:00 【Lu_ Ca】
brief introduction
AFNetworking4.0 It's right NSURLSession Encapsulation , Previous versions had NSURLConnection Encapsulation , Now it's abandoned .
Have a brief talk , Why? AF Discard the previous NSURLConnection encapsulation , In pairs NSURLSession encapsulation .
First ,NSURLSession Is in iOS7.0 Apple pushed it out . and NSURLSession And can support Http2.0 Of . Everybody knows Http Is based on TCP Agreed , In the early Http It's short connected , Every time you transmit data, you need to reconnect , Each time you connect, you need to shake hands three times , This leads to a waste of resources and time . then , stay Http2.0 Time to update Connection:keep-alive Options , This optimization item , Make the client and server in the same config Reuse the same TCP Connect , Reduced time per request , Improve the data transmission rate . therefore ,AFNetworking Also decisive change in pairs NSURLSession Encapsulation .
AFNetworking Five modules of
AFNetworking This tripartite library mainly includes the following five modules :
- NSURLSession Network communication module
- Reachability Network status monitoring module
- Security Network communication security policy module
- Serialization Serialization module
- UIKit Yes UIKit Expansion module for
The following is mainly about the use process , Initialization process and internal implementation process of the request method
initialization
First ,AFHttpSessonManager Inherited from AFURLSessonManager.
When we call the initialization method [AFHTTPSessionManager manager], Look at what has been done in the code ?
- (instancetype)initWithBaseURL:(NSURL *)url
sessionConfiguration:(NSURLSessionConfiguration *)configuration
{
self = [super initWithSessionConfiguration:configuration];
if (!self) {
return nil;
}
// 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;
}️: although AF Naming manager, however , The internal implementation is not a singleton , Instead, a new one will be created every time HttpSessonManager object .
- First, the parent class will be called (AFURLSessonManager) Initialization method of .
- to URL Format , add to “/”
- Set up requestSerializer and responseSerializer
Where the parent class (AFURLSessonManager) The initialization method of is mainly set configuration, And by setting maxConcurrentOperationCount = 1 Set up a serial queue . And the way of parsing 、 Monitor the network status and create a lock To ensure thread safety .
Request Method
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
for (NSString *headerField in headers.keyEnumerator) {
[request setValue:headers[headerField] forHTTPHeaderField:headerField];
}
if (serializationError) {
if (failure) {
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
}
return nil;
}
__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);
}
}
}];
return dataTask;
}In this way ,AF Returned a dataTask object . What have you done roughly ?
Through the first requestwithmethod Method to get a request object , When getting this object , Request type through request method get、head、delete To judge is to splice parameters directly to url Later, it is added to body in .
And then through the method dataTaskWithRequest Method , Will be on top of request Generate a task object . among addDelegateForDataTask Lieutenant general task and delegate Bind together . Every task There are corresponding agents .
In the specific request method (post、get、delete、put etc. ) in , For returned task Object call [dataTask resume]; Method .
[dataTask resume]
This is the last step in making a network request ,AF In the parent class , To the system resume Methods by method_exchangeImplementations Method and custom af_resume Method to exchange . And in the custom af_resume In the method, various result states are passed AFNSURLSessionTaskDidResumeNotification notice .
边栏推荐
- Activation functions sigmoid, tanh, relu in convolutional neural networks
- 【ARXIV2204】Simple Baselines for Image Restoration
- Clickhouse填坑记2:Join条件不支持大于、小于等非等式判断
- What tools do software testers need to know?
- 【CVPR2022】On the Integration of Self-Attention and Convolution
- What is the reason why the easycvr national standard protocol access equipment is online but the channel is not online?
- Configuration experiment of building virtual private network based on MPLS
- 塑料可以执行GB/T 2408 -燃烧性能的测定吗
- [daily one] visual studio2015 installation in ancient times
- Array or object, date operation
猜你喜欢
![[internal mental skill] - creation and destruction of function stack frame (C implementation)](/img/a9/81644ee9ffb74a5dc8ff1bc3977f49.png)
[internal mental skill] - creation and destruction of function stack frame (C implementation)

The default isolation level of MySQL is RR. Why does Alibaba and other large manufacturers change to RC?

Do you know several assertion methods commonly used by JMeter?

FreeRTOS learning (I)

How does Alibaba use DDD to split microservices?

RT_ Use of thread mailbox

Youxuan database participated in the compilation of the Research Report on database development (2022) of the China Academy of communications and communications

Reading notes of SMT practical guide 1

FreeRTOS startup process, coding style and debugging method

What SaaS architecture design do you need to know?
随机推荐
The first artificial intelligence security competition starts. Three competition questions are waiting for you to fight
Youxuan database participated in the compilation of the Research Report on database development (2022) of the China Academy of communications and communications
【CVPR2022】Multi-Scale High-Resolution Vision Transformer for Semantic Segmentation
[daily one] visual studio2015 installation in ancient times
FPGA:使用PWM波控制LED亮度
php7.1 连接sqlserver2008r2 如何测试成功
Dcgan:deep volume general adaptive networks -- paper analysis
微服务故障模式与构建弹性系统
Dynamic SQL and paging
HDU 2586 How far away ? (LCA multiplication method)
Research on the design of robot education in stem course
The difference between alter and confirm, prompt
猿辅导技术进化论:助力教与学 构想未来学校
Redis配置文件详解/参数详解及淘汰策略
面试了一位38岁程序员,听说要加班就拒绝了
POJ 1330 Nearest Common Ancestors (lca)
Redis type
Testcafe provides automatic waiting mechanism and live operation mode
What tools do software testers need to know?
MySQL 默认隔离级别是RR,为什么阿里等大厂会改成RC?