Blog:draveness
Pay attention to the warehouse and get updated in time: Ios-source-code-analyze
In this series of articles, I will analyze the source code of Afnetworking, learn more about how it is built, and how to complete the task of sending HTTP requests and building the network layer in daily life.
Afnetworking is one of the most indispensable components in IOS development today. Its github configuration is described below:
Perhaps the most important feature of all, however, was the amazing community of developers who use and contribute to afnet Working every day. Afnetworking powers Some of the most popular and critically-acclaimed apps on the IPhone, IPad, and Mac.
It can be said that the community of engineers using afnetworking makes it very important.
Overview
We are here today to delve into how this framework, which is closely related to our daily development, is implemented.
This is my understanding of the entire architecture of afnetworking, followed by a series of articles that will gradually analyze these modules.
In this article, we have two questions to understand:
How to use Nsurlsession to make an HTTP request
How to use afnetworking to make an HTTP request
Nsurlsession
NSURLSessionAnd the classes associated with it provide us with an API for downloading content, which provides a series of proxy methods to support authentication and background downloads.
A NSURLSession total of five steps are used to make HTTP requests and get data:
Instantiate one NSURLRequest/NSMutableURLRequest , set URL
- sharedSessionget through methodsNSURLSession
In session, the method is used to - dataTaskWithRequest:completionHandler: return aNSURLSessionDataTask
Send a message to data task - resume to begin this task
Encode data in Completionhandler, return a string
*request = [[NSMutableURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"https://github.com"]];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", dataStr); }];[task resume];
This section of code can be said to use the NSURLSession simplest piece of code to send a request, when you run this code will see a piece of GitHub home page HTML in the console.
<!DOCTYPE html><html lang="en" class=""> <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# object: http://ogp.me/ns/object# article: http://ogp.me/ns/article# profile: http://ogp.me/ns/profile#"> <meta charset=‘utf-8‘> ... </head> ...</html>
Afnetworking
The use of afnetworking is also relatively straightforward, using it to make HTTP requests with two steps
Generate an instance of Afhttpsessionmanager with the server's host address or domain name
Calling - GET:parameters:progress:success:failure: methods
*manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[[NSURL alloc] initWithString:@"hostname"]];[manager GET:@"relative_url" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"%@" ,responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"%@", error); }];
Note: In iOS9, Apple defaults to global HTTPs, and if you want to send an unsecured HTTP request, you need to add the following key-value pair in the Info.plist to make an unsecured HTTP request
Another thing to note is that Afnetworking receives the JSON-formatted response by default (because this is the framework on the IOS platform and generally does not need to be text/html), if you want to return HTML, you need to setacceptableContentTypes
Call stack for afnetworking
In this section we want to analyze the call stack of the above two methods, first of all to see the AFHTTPSessionManager initialization method- initWithBaseURL:
- [AFHTTPSessionManager initWithBaseURL:] - [AFHTTPSessionManager initWithBaseURL:sessionConfiguration:] - [AFURLSessionManager initWithSessionConfiguration:] - [NSURLSession sessionWithConfiguration:delegate:delegateQueue:] - [AFJSONResponseSerializer serializer] // 负责序列化响应 - [AFSecurityPolicy defaultPolicy] // 负责身份认证 - [AFNetworkReachabilityManager sharedManager] // 查看网络连接情况 - [AFHTTPRequestSerializer serializer] // 负责序列化请求 - [AFJSONResponseSerializer serializer] // 负责序列化响应
From the call stack of this initialization method, we can see very clearly the structure of this framework:
Where AFURLSessionManager is AFHTTPSessionManager the parent class
AFURLSessionManagerResponsible for generating NSURLSession the instance, management AFSecurityPolicy and AFNetworkReachabilityManager , to ensure the security of the request and view the network connection situation, it has an AFJSONResponseSerializer instance to serialize the HTTP response
AFHTTPSessionManagerHas its own AFHTTPRequestSerializer and AFJSONResponseSerializer to manage the serialization of requests and responses, while relying on the interface provided by the parent class to ensure security, monitor network status, and implement the core function of making HTTP requests
The initialization method is a good way to reveal the architecture of the afnetworking framework, and next we'll - GET:parameters:process:success:failure: look at how HTTP requests are sent by analyzing the call stack of another method:
-[Afhttpsessionmanager GET:parameters:process:success:failure:]-[ Afhttpsessionmanager DataTaskWithHTTPMethod:parameters:uploadProgress:downloadProgress:success:failure:] //return nsurlsessiondatatask #1-[Afhttprequestserializer RequestWithMethod:URLString:parameters:err Or:] //back nsmutableurlrequest-[Afurlsessionmanager DataTaskWithRequest:uploadProgress:down Loadprogress:completionhandler:] //back nsurlsessiondatatask #2-[Nsurlsession dataTaskWi Threquest:] //back nsurlsessiondatatask #3-[Afurlsessionmanager adddelegatefordatatask:u PloadProgress:downloadProgress:completionHandler:]-[afurlsessionmanagertaskdelegate init] -[Afurlsessionmanager Setdelegate:fortask:]-[nsurlsessiondatatask resume]
The #1 #2 #3 same Data task is returned here, and we can see that the method called at the same time is similar to the method that was #3 - [NSURLSession dataTaskWithRequest:] NSURLSession called only when the HTTP request was made - [NSURLSession dataTaskWithRequest:completionHandler:] . After the data task is returned in this place, we call the - resume method to execute the request and notify the agent when certain events are executedAFURLSessionManagerTaskDelegate
Summary
Afnetworking is actually only NSURLSession highly encapsulated, providing some easy-to-use APIs that allow us to make network requests in IOS development and build network layer components faster on them and provide a reasonable interface.
A brief introduction to-afnetworking in iOS development