AFNetworking的原理与使用

作者: CoderLocus | 来源:发表于2016-07-18 14:19 被阅读3266次

AFN 2.x 的六大模块:

NSURLConnection

主要对NSURLConnection进行了进一步的封装,包含以下核心的类:

  • AFURLConnectionOperation
  • AFHTTPRequestOperationManager
  • AFHTTPRequestOperation

AFURLConnectionOperation原理:

1:首先我们可以看到他创建了一个单例线程,用来处理AFN发起的所有请求任务。当然,现成也跟随着一个runLoop,AFN将这个runloop的模式设置成了NSDefaultRunLoopMode。但NSDefaultRunLoopMode是无法检测到connection的状 态的。这说明了,AFN将不会在这该线程处理connection完成后的UI刷新等工作,而是会将数据抛给主线程,让主线程去完成UI的刷新。
2:我们可以看到该类通过接受请求的字符串,创建了URLRequest以及NSURLConnection对象。从而去进行请求。
3:实现文件多次使用到了锁,可以保证数据的安全。当然他也实现了几个数据的NSCoping协议。
4:请求的创建、进行、取消、完成、暂停恢复、异常等问题及状态的控制。这里讲一下暂停和恢复。
暂停实际上将网络请求取消掉了。但是由于实现了nscoping协议,已经下载到数据得以保存下来。下次进行相同请求的时候,我们会将已经下载到的数据的节 点一起发送给服务器,告诉服务器这些部门的数据我们不需要了,服务器根据我发送的返回节点给我返回相应的数据即可。从而实现了暂停和恢复功能,也就是断点 续传。
5:operation方法的重写。自行google,这里不赘述。
6:状态的各种控制方法的实现以及发送状态改变的通知


Thread.png

NSURLSession

主要对象NSURLSession对象进行了进一步的封装,包含以下核心的类:

  • AFHTTPSessionManager
  • AFURLSessionManager

Reachability

提供了与网络状态相关的操作接口,包含以下核心的类:

  • AFNetworkReachabilityManager

但实际使用我不建议使用,可以使用苹果公司自己写的那个Reachability库,因为有些无线网络,AFN会返回AFNetworkReachabilityStatusUnknown,而不是AFNetworkReachabilityStatusReachableViaWiFi。自己亲身体会,仅供参考。

Security

提供了与安全性相关的操作接口,包含以下核心的类:

  • AFSecurityPolicy

Serialization

提供了与解析数据相关的操作接口,包含以下核心的类:

  • AFURLRequestSerialization
  • AFHTTPRequestSerializer
  • AFJSONRequestSerializer
  • AFPropertyListRequestSerializer
  • AFURLResponseSerialization
  • AFHTTPResponseSerializer
  • AFJSONResponseSerializer
  • AFXMLParserResponseSerializer
  • AFXMLDocumentResponseSerializer (Mac OS X)
  • AFPropertyListResponseSerializer
  • AFImageResponseSerializer
  • AFCompoundResponseSerializer

UIKit

提供了大量网络请求过程中与UI界面显示相关的操作接口,通常用于网络请求过程中提示,使用户交互更加友好,包含以下核心的分类/类:

  • AFNetworkActivityIndicatorManager
  • UIActivityIndicatorView+AFNetworking
  • UIAlertView+AFNetworking
  • UIButton+AFNetworking
  • UIImageView+AFNetworking
  • UIKit+AFNetworking
  • UiprogressView+AFNetworking
  • UIRefreshControl+AFNetworking
  • UIWebView+AFNetworking

在3.x之后:

由于App Store策略要求所有iOS应用必须包含对IPv6-only网络的支持。自2016年6月1日开始,所有提交至苹果App Store的应用申请必须要兼容面向硬件识别和网络路由的最新互联网协议--IPv6-only标准。
我们是可以通过NSURLSession和CFNetwork APIs兼容该协议。所以AFNetworking摒弃了NSURLConnection。通过使用NSURLSession来支持IPv6-only协议。
而且由于苹果官方正逐渐摒弃UIAlertView,所以AFNetworking也取消了对UIAlertView+AFNetworking的扩展。也增加了AFImageDownloader和AFAutoPurgingImageCache。

先说一下NSURLSession的使用吧(有不对之处,敬请指点!),毕竟现在要支持IPv6。

  • AFURLSessionManager
    AFURLSessionManager基于NSURLSessionConfiguration创建并管理一个NSURLSession对象,该对象遵守了<NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>协议。

创建一个下载任务:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://JingQL.com/download"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request
                                                                 progress:nil
                                                              destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
                                                                NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                                                                                                      inDomain:NSUserDomainMask
                                                                                                                             appropriateForURL:nil
                                                                                                                                        create:NO
                                                                                                                                         error:nil];
                                                                return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
                                                            }
                                                        completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                                                            NSLog(@"File downloaded to: %@", filePath);
                                                        }];
[downloadTask resume];

创建一个上传任务:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://JingQL.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request
                                                           fromFile:filePath
                                                           progress:nil
                                                  completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                                                      if (error) {
                                                          NSLog(@"Error: %@", error);
                                                      } else {
                                                          NSLog(@"Success: %@ %@", response, responseObject);
                                                      }
                                                  }];
[uploadTask resume];

创建一个带有进度的上传请求任务

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://http://JingQL.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
              uploadTaskWithStreamedRequest:request
              progress:^(NSProgress * _Nonnull uploadProgress) {
                  
                  dispatch_async(dispatch_get_main_queue(), ^{
                      
                      [ProgressView setProgress:uploadProgress.fractionCompleted];
                  });
              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                  } else {
                      NSLog(@"%@ %@", response, responseObject);
                  }
              }];

[uploadTask resume];

创建一个请求数据任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@ %@", response, responseObject);
    }
}];
[dataTask resume];

参考:AFNetWorking的实现原理ANF-GitHub

相关文章

网友评论

  • MooneyWang:虽说NSURLSession取代了NSURLConnection,但是NSURLConnection也是支持IPv6的。
    CoderLocus:@mooney_wang 谢谢指点,主要由于苹果官方只给出了NSURLSession和CFNetwork的API不需要改变,但是并没有提及到NSURLConnection。的确,有人测试过NSURLConnection在iOS9上是支持IPv6的,但现在很多应用最低还需要支持iOS7,但NSURLConnection在iOS8.4就不能正常访问了。

本文标题:AFNetworking的原理与使用

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