请求实现
AFNetworiking是基于苹果网络框架的封装,要了解AFNetworiking的实现,
我们先来看看怎么自己实现一次简单的网络请求,先熟悉一下流程.
如下代码:
- (void)requestPost
{
//1.请求参数
NSDictionary *dicParam = @{@"key":@"value"};
NSError *error = nil;
NSData *bodyData = [NSJSONSerialization dataWithJSONObject:dicParam options:0 error:&error];
if (error) {
return;
}
NSString *baseUrl = @"https://xxx.com";// 请求 url
//2.create request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:baseUrl]];
[request setValue:[NSString stringWithFormat:@"%ld", (long) [bodyData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPMethod:@"POST"];//请求类型配置
[request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
[request setHTTPBody:bodyData];
//3.create Configuration
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.timeoutIntervalForRequest = 15.0;
//4.发起请求,这里选用delegate的方式接收返回结果
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
[dataTask resume];
}
遵循NSURLSessionDataDelegate协议,实现协议方法,接收回调
//5.接收回调数据
#pragma mark - NSURLSessionDataTaskDelegate
-(void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveData:(nonnull NSData *)data
{
NSLog(@"这个就是请求返回数据:%@",data);
}
由上面代码可看出,一次简单的网络请求,简单分为5步:
1.配置请求参数,请求URL;
2.创建request,并设置request的参数;
3.创建NSURLSessionConfiguration,并配置参数;
4.发起请求(此处为delegate方式);
5.接收回调,处理请求结果,请求完成.
由于iOS9后不支持NSURLConnection,第4步发起请求我们使用的是NSURLSession
AF内请求类型有:GET,HEAD,POST,PUT,DELETE.
AFNetworking的网路请求实现
AF实现网路请求两个核心类
AFHTTPSessionManager,AFURLSessionManager.(其中AFHTTPSessionManager 继承自AFURLSessionManager)
@interface AFHTTPSessionManager : AFURLSessionManager <NSSecureCoding, NSCopying>
其中AFHTTPSessionManager类我们可以理解为管理request和sessionConfiguration的类,对应上面1,2,3步
AFURLSessionManage为管理发起和接收请求的类,对应上面的4,5步
具体实现
此处我们以AF的POST方法实现举例,以下只挑关键的方法说明;
使用AF的POST请求,我们首先要创建AFHTTPSessionManager对象,调用AFHTTPSessionManager的实例方法POST:
创建AFHTTPSessionManager对象,
有没有上面2,3步的感觉?
- (AFHTTPSessionManager *)sessionManager
{
if (_sessionManager == nil) {
_sessionManager = [AFHTTPSessionManager manager];//manager 也是每次都创建
//返回数据自动解析 当前没有解析 返回的是二进制
[_sessionManager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
//设置responseSerializer的值
[_sessionManager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"image/png", nil]];//类似第二步的request设置
[_sessionManager.requestSerializer setTimeoutInterval:15.0];//类似第三步的SessionConfiguration设置
}
return _sessionManager;
}
上面是通过通过类方法manager创建的对象,对应下图,可以看到此时NSURLSessionConfiguration为nil
接着调用POST方法,看我添加的注释,先创建了request,接着调用请求方法
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *, id))success
failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
NSError *serializationError = nil;
//注意,此处返回了request,下面需要用到改request
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
return nil;
}
__block NSURLSessionDataTask *dataTask = nil;
//调用父类AFURLSessionManager的方法,通过上面的request发起请求
dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) {
if (failure) {
failure(dataTask, error);
}
} else {
if (success) {
success(dataTask, responseObject);
}
}
}];
return dataTask;
}
请求方法内部实现,在自己的队列内同步发起请求,然后设置代理,此方法为AFURLSessionManager的方法
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
__block NSURLSessionDataTask *dataTask = nil;
//以下对应咱们说的第4步,发起请求,设置delegate
//在自己的队列内执行同步方法
dispatch_sync(url_session_manager_creation_queue(), ^{
//发起请求
dataTask = [self.session dataTaskWithRequest:request];
});
//设置delegate
[self addDelegateForDataTask:dataTask completionHandler:completionHandler];
return dataTask;
}
代理方法实现,接收数据
#pragma mark - NSURLSessionDataTaskDelegate
//回调内接收数据,对应第5步
- (void)URLSession:(__unused NSURLSession *)session
dataTask:(__unused NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
[self.mutableData appendData:data];
}
到此,整个AFNetworking的POST请求流程大致过程结束,get到的朋友点下❤️
AF网络请求的其他细节请听下回分解.