一 .实现步骤
NSString *requestUrl =@"";
AFHTTPSessionManager *manager =[[AFHTTPSessionManager alloc]init]; [manager GET:requestURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task,id _Nullable responseObject) {
NSLog(@"请求成功了!");
NSLog(@"%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败了!");
}];
1 .上面是封装在最外层的方法,点进去是不管是get还是post调用的都是全能方法- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters
progress:(void (^)(NSProgress * _Nonnull))downloadProgress
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
URLString:URLString
parameters:parameters
uploadProgress:nil
downloadProgress:downloadProgress
success:success
failure:failure];
[dataTask resume];
return dataTask;
}
2.对请求进行序列化(序列化是将数据结构转为二进制串,既可以理解为将用户名,密码等字符串转为二进制流),如果序列化失败,就执行failure block 否则继续3
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
success:(void (^)(NSURLSessionDataTask *, id))success
failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
NSError *serializationError = nil;
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;
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;
}
3.配置 NSMutableURLRequest 对象就需要配置 NSURLSessionDataTask 对象了。主要分为2个步骤,第一个步骤是创建 NSURLSessionDataTask 对象实例,第二个步骤是给NSURLSessionDataTask 对象实例设置 Delegate。用于实时了解网络请求的过程。
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
success:(void (^)(NSURLSessionDataTask *, id))success
failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
NSError *serializationError = nil;
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;
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;
}
4 .对每一个NSURLSessionDataTask的dataTask增加代理的具体实现,对dataTask设置请求之后的回调Delegate和处理block,AFN 的代理统一使用AFURLSessionManagerTaskDelegate对象来管理NSURLSessionTask网络请求过程中的回调,然后在传入AFN进行管理,如代码所示AFURLSessionManagerTaskDelegate 接管了NSURLSessionTaskDelegate,NSURLSessionDataDelegate,NSURLSessionDownloadDelegate的各种回调,然后做内部处理。这也是第三方网络请求框架的重点,让网络请求更加易用,好用
- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask
uploadProgress:(nullable void(^)(NSProgress *uploadProgress)) uploadProgressBlock
downloadProgress:(nullable void(^)(NSProgress *downloadProgress)) downloadProgressBlock
completionHandler:(void(^)(NSURLResponse *response,idresponseObject, NSError *error))completionHandler
{
AFURLSessionManagerTaskDelegate *delegate= [[AFURLSessionManagerTaskDelegate alloc] init];
delegate.manager = self;
delegate.completionHandler = completionHandler;
dataTask.taskDescription = self.taskDescriptionForSessionTasks;
[self setDelegate:delegate forTask:dataTask];
delegate.uploadProgressBlock = uploadProgressBlock;
delegate.downloadProgressBlock = downloadProgressBlock;
}
AFNetworking 3.0 实现完全基于NSURLSessionTask进行封装,NSURLSessionTask 是苹果在iOS7 推出的网络请求api。AF支持https,网络数据请求,文件上传,文件下载,监听手机网络状态。AFHttpSessionManager 继承 AFURLSessionManager 对网络请求进行管理,使用AFURLRequestSerialization 对网络请求进行封装,使用AFURLReponseSerialization 响应体进行处理,使用AFSecurityPolicy 对服务器证书进行校验。支持https协议,支持本地证书和服务器证书进行对比验证,AF要求ios7或以上系统。AF数据传递主要使用block 和 notifacation的方式。
post和get的不同:如果是 Post 请求,那么请求参数是没有拼接在 URL 上面,而是放在 body 上,这是 Post 和 Get 请求的最大区别了,其他过程和Get 请求并没有太多区别。
总结
AFN发起Get请求主要分为以下步骤:
1.创建NSURLSessionDataTask
2.配置NSURLSessionDataTask
3.设置NSURLSessionDataTask的Delegate
4.调用NSURLSessionDataTask的resume方法开始请求
5.在Delegate的方法里面处理网络请求的各个过程
6.清理NSURLSessionDataTask的配置
其实也就是使用NSURLSessionDataTask的步骤,AFN在这几个步骤加了一些封装,让我们的使用更简单。
补充:NSURLSession是2013年iOS 7发布的用于替代NSURLConnection的,iOS 9之后NSURLConnection彻底推出历史舞台
使用: 以get请求为例
1.配置请求资源
NSURL *url = [NSURL URLWithString:@"http://api.nohttp.net/method?name=yanzhenjie&pwd=123"];
2.创建一个NSRequest请求对象
// 创建Request请求NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 配置Request请求
// 设置请求方法[request setHTTPMethod:@"GET"];
// 设置请求超时 默认超时时间60s[request setTimeoutInterval:10.0];
// 设置头部参数[request addValue:@"gzip"forHTTPHeaderField:@"Content-Encoding"];
//或者下面这种方式 添加所有请求头信息request.allHTTPHeaderFields=@{@"Content-Encoding":@"gzip"};
//设置缓存策略[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
3.创建NSURLSession会话对象
NSURLSession *sharedSession = [NSURLSession sharedSession];
// 构造NSURLSessionConfigurationNSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// 构造NSURLSession,网络会话;NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
4.) 创建NSURLSessionTask对象,然后执行
// 构造NSURLSessionTask,会话任务;NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 请求失败,打印错误信息if (error) {
NSLog(@"get error :%@",error.localizedDescription);
}
//请求成功,解析数据else {
// JSON数据格式解析idobject= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
// 判断是否解析成功if (error) {
NSLog(@"get error :%@",error.localizedDescription);
}else {
NSLog(@"get success :%@",object);
// 解析成功,处理数据,通过GCD获取主队列,在主线程中刷新界面。dispatch_async(dispatch_get_main_queue(), ^{
// 刷新界面.... });
}
}
}];
更详细的链接:https://www.cnblogs.com/whoislcj/p/6369717.html