AFNetworking 使用说明

来源:互联网 发布:淘宝网短袖男装 编辑:程序博客网 时间:2024/05/29 03:24

AFNetworking

谷歌翻译 

AFNetworking 是为 iOS 和 Mac OS X 。它是建立在之上的愉快的网络库 基金会的URL 加载系统   ,延长内置到可可的功能强大的高级网络抽象。   它有一个模块化的架构,设计精良,功能丰富的 API ,是一个欢乐的使用。

也许,最重要的功能,但是,是谁使用,每天贡献 AFNetworking 开发商惊人的社群。  AFNetworking 一些权力在 iPhone , iPad 和 Mac 的最流行和广受好评的应用程序。

选择 AFNetworking 你的下一个项目,或迁移在你现有的项目 - 你很高兴你没有!

如何开始

  • 下载 AFNetworking 并尝试了包括 Mac 和 iPhone 应用程序的例子
  • 阅读 “ 入门 ” 指南   ,   常见问题   ,或 对维基的其他文章
  • 退房的 文档 进行全面审视所有的 API 提供 AFNetworking
  • 有问题吗?   堆栈溢出 是找到答案的最佳场所

安装与 CocoaPods

CocoaPods 是一个依赖经理的 Objective-C ,它能够自动并简化使用像AFNetworking 的第三方库在项目的进程。   请参阅 “ 入门 ” 指南获取更多信息   。

Podfile

  平台 : IOS , '7 .0'

  荚 “AFNetworking” , “ ~ > 2.0”

2.0

AFNetworking 2.0 是一个重大更新的框架。   建设 2 年的发展,这个新版本引入了强大的新功能,同时提供了一个简单的升级路径,为现有的用户。

阅读 AFNetworking 2.0 迁移指南 为建筑和 API 的变化的概述。

最新消息

  • 重构架构
  • 支持 NSURLSession
  • 序列化模块
  • 扩大的 UIKit 扩展
  • 实时功能与 火箭

要求

AFNetworking 2.0 和更高要求的 Xcode 5 ,确定目标的的 iOS 6.0 及以上版本,或Mac OS 10.8 山狮(   64 位与现代可可运行时   )及以上。

对于与 iOS 5 或 Mac OS X 10.7 的兼容性,请使用 最新的 1.x 的版本   。

对于与 iOS 4.3 或 Mac OS X 10.6 的兼容性,请使用 最新的 0.10.x 版本   。

建筑

NSURLConnection 的

  • AFURLConnectionOperation
  • AFHTTPRequestOperation
  • AFHTTPRequestOperationManager

NSURLSession ( iOS 的 7 / Mac OS X 的 10.9 )

  • AFURLSessionManager
  • AFHTTPSessionManager

序列化

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

附加功能

  • AFSecurityPolicy
  • AFNetworkReachabilityManager

用法

HTTP 请求营运经理

AFHTTPRequestOperationManager 封装与 Web 应用程序进行通信通过 HTTP ,包括要求制作,响应序列化,网络可达性监控和安全性,以及要求经营管理的常见模式。

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 格式编码的请求

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 多部分请求

AFHTTPRequestOperationManager *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 创建和管理一个 NSURLSession 根据指定的对象NSURLSessionConfiguration 对象,这符合 <NSURLSessionTaskDelegate>   ,  <NSURLSessionDataDelegate>   ,   <NSURLSessionDownloadDelegate> 和<NSURLSessionDelegate>   。

创建下载任务

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 *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) firstObject]];    return [documentsDirectoryPath 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://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];

创建上传任务的多部分请求,与进展

   

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];

创建数据任务

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];

请求序列化

请求序列化创建 URL 字符串,编码参数作为一个查询字符串或 HTTP 主体请求。

NSString *URLString = @"http://example.com";NSDictionary *parameters = @{@"foo":@"bar", @"baz": @[@1,@2, @3]};

查询字符串参数编码

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters];GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

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 编码参数

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];POST http://example.com/Content-Type: application/json{"foo": "bar", "baz": [1,2,3]}

网络可达性管理

AFNetworkReachabilityManager 监控领域的可达性,并为 WWAN 和 WiFi 网络接口的地址。

共享网络可达性

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));}];

与基本 URL 的 HTTP 经理

当 baseURL 提供,网络可达性的作用范围是该基地 URL 的主机。

NSURL *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;    }}];

安全策略

AFSecurityPolicy 评估对固定 X.509 证书和通过安全连接的公共密钥服务器信任。

新增固定 SSL 证书到你的应用有助于防止人在这方面的中间人攻击和其他安全漏洞。   应用程序处理敏感的客户数据或财务信息我们强烈建议路线在使用 SSL 钉扎配置和启用 HTTPS 连接的所有通信。

使无效的 SSL 证书

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];manager.securityPolicy.allowInvalidCertificates =YES; // 不建议在生产

AFHTTPRequestOperation

AFHTTPRequestOperation 是的一个子类 AFURLConnectionOperation 使用 HTTP或 HTTPS 协议请求。   它封装的接受状态代码和内容类型,这决定了请求的成功或失败的概念。

虽然 AFHTTPRequestOperationManager 通常是去提出要求的最佳途径,  AFHTTPRequestOperation 可以单独使用。

GET with 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];

操作的批处理

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];

单元测试

AFNetworking 包括一套内部的测试子目录中的单元测试。   为了运行单元测试,你必须通过 CocoaPods 安装测试的依赖关系:

一旦测试的依赖安装,你可以通过在 Xcode 的 ' 的 iOS 测试 “ 和 ”OS X 的测试 “ 计划,执行测试套件。

使用 xctool

测试也可以通过命令行或在一个持续集成环境中运行 xctool   ,它可以安装 自制软件   :

 $ brew install xctool --HEAD  

一旦 xctool 安装,你可以通过执行该套件 rake test   。

0 0
原创粉丝点击