AFN文档中文翻译以及简单使用说明

来源:互联网 发布:男人月薪4500 知乎 编辑:程序博客网 时间:2024/04/26 23:18

AFNetworking2.4.1解析

  • AFNetworking2.4.1解析
  • AFNetworking官网(点击进入)

AFNetworking翻译注释

  • Architecture(结构)
    • NSURLConnection
    • AFURLConnectionOperation
    • AFHTTPRequestOperation
    • AFHTTPRequestOperationManager
    • NSURLSession (iOS 7)
    • AFURLSessionManager
    • AFHTTPSessionManager
    • Serialization(序列化)
    • AFURLRequestSerialization
      • AFHTTPRequestSerializer
      • AFJSONRequestSerializer
      • AFPropertyListRequestSerializer
    • AFURLResponseSerialization
      • AFHTTPResponseSerializer
      • AFJSONResponseSerializer
      • AFXMLParserResponseSerializer
      • AFXMLDocumentResponseSerializer (Mac OS X)
      • AFPropertyListResponseSerializer
      • AFImageResponseSerializer
      • AFCompoundResponseSerializer
  • Additional Functionality
    • AFSecurityPolicy
    • AFNetworkReachabilityManager

Usage(使用)

  • HTTP Request Operation Manager(HTTP请求操作管理器)
    AFHTTPRequestOperationManager encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management.
    AFHTTPRequestOperationManage
    将通用的与服务器应用交互的操作封装了起来,包括了请求的创建,回复的序列化,网络指示器的监测,安全性,当然还有请求操作的管理。

  • GET Request(GET请求)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject){NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error){NSLog(@"Error: %@", error);}];
  • POST URL-Form-Encoded Request(附带表单编码的POST请求)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];NSDictionary *parameters = @{@"foo": @"bar"};[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error){NSLog(@"Error: %@", error);}];````- POST Multi-Part Request(复杂的POST请求)<div class="se-preview-section-delimiter"></div>```objcAFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];NSDictionary *parameters = @{@"foo": @"bar"};NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData){[formData appendPartWithFileURL:filePath name:@"image" error:nil];} success:^(AFHTTPRequestOperation *operation, id responseObject){NSLog(@"Success: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error){NSLog(@"Error: %@", error);}];
  • AFURLSessionManager
    AFURLSessionManager creates and manages an NSURLSession object based on a specified NSURLSessionConfiguration object, which conforms to , , , and .
    AFURLSessionManager 创建了一个管理一个NSURLSession的对象,基于一个指定的NSURLSessionConfiguration对象,它与以下的这些协议融合在一起(, , ,)。
  • Creating a Download Task(创建一个下载任务)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];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];
  • Creating an Upload Task(创建一个上传任务)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.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];
  • Creating an Upload Task for a Multi-Part Request, with Progress(创建一个复杂的请求,并附带进度)
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.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]];NSProgress *progress = nil;NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {if (error) {NSLog(@"Error: %@", error);} else {NSLog(@"%@ %@", response, responseObject);}}];[uploadTask resume];
  • Creating a Data Task(创建一个数据任务)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];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];
  • Request Serialization(请求序列化)
    Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
    请求序列化器会从URL字符串创建请求,编码参数,查找字符串或者是HTTPbody部分。
NSString *URLString = @"http://example.com";NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
  • Query String Parameter Encoding(查询string的编码)
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
  • URL Form Parameter Encoding(查询URL表单形式参数的编码)
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];POST http://example.com/Content-Type: application/x-www-form-urlencodedfoo=bar&baz[]=1&baz[]=2&baz[]=3
  • JSON Parameter Encoding(查询json参数的编码)
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];POST http://example.com/Content-Type: application/json{"foo": "bar", "baz": [1,2,3]}
  • Network Reachability Manager(监测网络管理器)
    AFNetworkReachabilityManager monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
    • AFNetworkReachabilityManager 监测域名以及IP地址的畅通性,对于WWAN以及WiFi的网络接口都管用。
    • Shared Network Reachability(单例形式检测网络畅通性)
      “`objc
      [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { NSLog(@”Reachability: %@”, AFStringFromNetworkReachabilityStatus(status));}];
- HTTP Manager with Base URL(用基本的URL管理HTTP)When a baseURL is provided, network reachability is scoped to the host of that base URL.如果提供了一个基本的URL地址,那个基本URL网址的畅通性就会被仔细的监测着。```objcNSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];NSOperationQueue *operationQueue = manager.operationQueue;[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {switch (status) {case AFNetworkReachabilityStatusReachableViaWWAN:case AFNetworkReachabilityStatusReachableViaWiFi:[operationQueue setSuspended:NO];break;case AFNetworkReachabilityStatusNotReachable:default:[operationQueue setSuspended:YES];break;}}];<div class="se-preview-section-delimiter"></div>
  • Security Policy
    AFSecurityPolicy evaluates server trust against pinned X.509 certificates and public keys over secure connections.
    Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
    Allowing Invalid SSL Certificates(允许不合法的SSL证书)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production<div class="se-preview-section-delimiter"></div>
  • AFHTTPRequestOperation
    AFHTTPRequestOperation is a subclass of AFURLConnectionOperation for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
    Although AFHTTPRequestOperationManager is usually the best way to go about making requests, AFHTTPRequestOperation can be used by itself.
    AFHTTPRequestOperation继承自AFURLConnectionOperation,使用HTTP以及HTTPS协议来处理网络请求。它封装成了一个可以令人接受的代码形式。当然AFHTTPRequestOperationManager 目前是最好的用来处理网络请求的方式,但AFHTTPRequestOperation 也有它自己的用武之地。
  • GET with AFHTTPRequestOperation(使用AFHTTPRequestOperation)
NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];NSURLRequest *request = [NSURLRequest requestWithURL:URL];AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];op.responseSerializer = [AFJSONResponseSerializer serializer];[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){NSLog(@"JSON: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error){ NSLog(@"Error: %@", error);}];[[NSOperationQueue mainQueue] addOperation:op];<div class="se-preview-section-delimiter"></div>
  • Batch of Operations(许多操作一起进行)
NSMutableArray *mutableOperations = [NSMutableArray array];for (NSURL *fileURL in filesToUpload){NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData){[formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];}];AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];[mutableOperations addObject:operation];}NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations){NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);} completionBlock:^(NSArray *operations){ NSLog(@"All operations in batch complete");}];[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];<div class="se-preview-section-delimiter"></div>
  • NSURLConnection 组件 (iOS 6 & 7)
    • AFURLConnectionOperation - NSOperation 的子类,负责管理 NSURLConnection 并且实现其 delegate 方法。
    • AFHTTPRequestOperation - AFURLConnectionOperation 的子类,用于生成 HTTP 请求,可以区别可接受的和不可接受的状态码及内容类型。2.0 版本中的最大区别是,你可以直接使用这个类,而不用继承它,原因可以在“序列化”一节中找到。
    • AFHTTPRequestOperationManager - 包装常见 HTTP web 服务操作的类,通过AFHTTPRequestOperation 由 NSURLConnection 支持。
      NSURLSession 组件 (iOS 7)
    • AFURLSessionManager - 创建、管理基于 NSURLSessionConfiguration 对象的NSURLSession 对象的类,也可以管理 session 的数据、下载/上传任务,实现 session 和其相关联的任务的 delegate 方法。因为 NSURLSession API 设计中奇怪的空缺,任何和NSURLSession 相关的代码都可以用 AFURLSessionManager 改善。
    • AFHTTPSessionManager - AFURLSessionManager 的子类,包装常见的 HTTP web 服务操作,通过 AFURLSessionManager 由 NSURLSession 支持。
  • 序列化
    • AFURLRequestSerializer> - 符合这个协议的对象用于处理请求,它将请求参数转换为 query string 或是 entity body 的形式,并设置必要的 header。那些不喜欢 AFHTTPClient使用 query string 编码参数的家伙,你们一定喜欢这个。
    • - 符合这个协议的对象用于验证、序列化响应及相关数据,转换为有用的形式,比如 JSON 对象、图像、甚至基于 Mantle 的模型对象。相比没完没了地继承 AFHTTPClient,现在 AFHTTPRequestOperation 有一个 responseSerializer 属性,用于设置合适的 handler。同样的,再也没有没用的受 NSURLProtocol 启发的 request operation 类注册,取而代之的还是很棒的 responseSerializer 属性。
  • 安全性
    AFNetworking 现在带有内置的 SSL pinning 支持,这对于处理敏感信息的应用是十分重要的。
    • AFSecurityPolicy - 评估服务器对安全连接针对指定的固定证书或公共密钥的信任。tl;dr 将你的服务器证书添加到 app bundle,以帮助防止 中间人攻击。
  • 可达性
    • 从 AFHTTPClient 解藕的另一个功能是网络可达性。现在你可以直接使用它,或者使用AFHTTPRequestOperationManager / AFHTTPSessionManager 的属性。
    • AFNetworkReachabilityManager - 这个类监控当前网络的可达性,提供回调 block 和 notificaiton,在可达性变化时调用。
  • 实时性
    • AFEventSource - EventSource DOM API 的 Objective-C 实现。建立一个到某主机的持久 HTTP 连接,可以将事件传输到事件源并派发到听众。传输到事件源的消息的格式为JSON Patch 文件,并被翻译成 AFJSONPatchOperation 对象的数组。可以将这些 patch operation 应用到之前从服务器获取的持久性数据集。
NSURL *URL = [NSURL URLWithString:@"http://example.com"]; AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:URL];[manager GET:@"/resources" parameters:nil success:NSURLSessionDataTask *task, id responseObject { [resources addObjectsFromArray:responseObject[@"resources"]];<div class="se-preview-section-delimiter"></div>
[manager SUBSCRIBE:@"/resources" usingBlock:NSArray *operations, NSError *error { for (AFJSONPatchOperation *operation in operations) { switch (operation.type) { case AFJSONAddOperationType: [resources addObject:operation.value]; break; default: break; } } } error:nil]; } failure:nil];
  • UIKit 扩展
    • AFNetworkActivityIndicatorManager:在请求操作开始、停止加载时,自动开始、停止状态栏上的网络活动指示图标。
    • UIImageView+AFNetworking:增加了 imageResponseSerializer 属性,可以轻松地让远程加载到 image view 上的图像自动调整大小或应用滤镜。比如,AFCoreImageSerializer可以在 response 的图像显示之前应用 Core Image filter。
    • UIButton+AFNetworking (新):与 UIImageView+AFNetworking 类似,从远程资源加载image 和 backgroundImage。
    • UIActivityIndicatorView+AFNetworking (新):根据指定的请求操作和会话任务的状态自动开始、停止 UIActivityIndicatorView。
    • UIProgressView+AFNetworking (新):自动跟踪某个请求或会话任务的上传/下载进度。
    • UIWebView+AFNetworking (新): 为加载 URL 请求提供了更强大的API,支持进度回调和内容转换。

3.中文详细解析
解析一
解析二
解析三

- Batch of Operations(许多操作一起进行)```objcNSMutableArray *mutableOperations = [NSMutableArray array];for (NSURL *fileURL in filesToUpload){NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData){[formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];}];AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];[mutableOperations addObject:operation];}NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations){NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);} completionBlock:^(NSArray *operations){ NSLog(@"All operations in batch complete");}];[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
  • NSURLConnection 组件 (iOS 6 & 7)
    • AFURLConnectionOperation - NSOperation 的子类,负责管理 NSURLConnection 并且实现其 delegate 方法。
    • AFHTTPRequestOperation - AFURLConnectionOperation 的子类,用于生成 HTTP 请求,可以区别可接受的和不可接受的状态码及内容类型。2.0 版本中的最大区别是,你可以直接使用这个类,而不用继承它,原因可以在“序列化”一节中找到。
    • AFHTTPRequestOperationManager - 包装常见 HTTP web 服务操作的类,通过AFHTTPRequestOperation 由 NSURLConnection 支持。
      NSURLSession 组件 (iOS 7)
    • AFURLSessionManager - 创建、管理基于 NSURLSessionConfiguration 对象的NSURLSession 对象的类,也可以管理 session 的数据、下载/上传任务,实现 session 和其相关联的任务的 delegate 方法。因为 NSURLSession API 设计中奇怪的空缺,任何和NSURLSession 相关的代码都可以用 AFURLSessionManager 改善。
    • AFHTTPSessionManager - AFURLSessionManager 的子类,包装常见的 HTTP web 服务操作,通过 AFURLSessionManager 由 NSURLSession 支持。
  • 序列化
    • AFURLRequestSerializer> - 符合这个协议的对象用于处理请求,它将请求参数转换为 query string 或是 entity body 的形式,并设置必要的 header。那些不喜欢 AFHTTPClient使用 query string 编码参数的家伙,你们一定喜欢这个。
    • - 符合这个协议的对象用于验证、序列化响应及相关数据,转换为有用的形式,比如 JSON 对象、图像、甚至基于 Mantle 的模型对象。相比没完没了地继承 AFHTTPClient,现在 AFHTTPRequestOperation 有一个 responseSerializer 属性,用于设置合适的 handler。同样的,再也没有没用的受 NSURLProtocol 启发的 request operation 类注册,取而代之的还是很棒的 responseSerializer 属性。
  • 安全性
    AFNetworking 现在带有内置的 SSL pinning 支持,这对于处理敏感信息的应用是十分重要的。
    • AFSecurityPolicy - 评估服务器对安全连接针对指定的固定证书或公共密钥的信任。tl;dr 将你的服务器证书添加到 app bundle,以帮助防止 中间人攻击。
  • 可达性
    • 从 AFHTTPClient 解藕的另一个功能是网络可达性。现在你可以直接使用它,或者使用AFHTTPRequestOperationManager / AFHTTPSessionManager 的属性。
    • AFNetworkReachabilityManager - 这个类监控当前网络的可达性,提供回调 block 和 notificaiton,在可达性变化时调用。
  • 实时性

    • AFEventSource - EventSource DOM API 的 Objective-C 实现。建立一个到某主机的持久 HTTP 连接,可以将事件传输到事件源并派发到听众。传输到事件源的消息的格式为JSON Patch 文件,并被翻译成 AFJSONPatchOperation 对象的数组。可以将这些 patch operation 应用到之前从服务器获取的持久性数据集。
  • UIKit 扩展

    • AFNetworkActivityIndicatorManager:在请求操作开始、停止加载时,自动开始、停止状态栏上的网络活动指示图标。
    • UIImageView+AFNetworking:增加了 imageResponseSerializer 属性,可以轻松地让远程加载到 image view 上的图像自动调整大小或应用滤镜。比如,AFCoreImageSerializer可以在 response 的图像显示之前应用 Core Image filter。
    • UIButton+AFNetworking (新):与 UIImageView+AFNetworking 类似,从远程资源加载image 和 backgroundImage。
    • UIActivityIndicatorView+AFNetworking (新):根据指定的请求操作和会话任务的状态自动开始、停止 UIActivityIndicatorView。
    • UIProgressView+AFNetworking (新):自动跟踪某个请求或会话任务的上传/下载进度。
    • UIWebView+AFNetworking (新): 为加载 URL 请求提供了更强大的API,支持进度回调和内容转换。

3.中文详细解析
解析一
解析二
解析三

0 0
原创粉丝点击